【问题标题】:django template conditional htmldjango模板条件html
【发布时间】:2014-04-26 18:10:41
【问题描述】:

我不确定标题在技术上是否正确(抱歉,我是 python+django 的新手)

我有一个模板页面,它显示应用程序是运行还是停止取决于其状态。例如:

如果应用程序正在运行,我想显示:

<div class="lt">
    <a class="play" title="App running">
        <span class="text_play">Running</span>
    </a>
</div>
<div class="rt">
    <input type="submit" onclick="stop_app()" value="stop" class="stop">
</div>

如果应用程序未运行,则改为显示:

<div class="lt">
    <input type="submit" onclick="star_app()" value="start" class="play">
</div>
<div class="rt">
    <a class="stop" title="Application is not running">
        <span class="test_stop">Not Running</span>
    </a>
</div>

这是一种简化的 html,但我的意思是如何避免重复自己?

模板传递了一个应用程序字典,它会迭代以显示所有应用程序及其状态(运行/停止)。所以目前我正在迭代字典两次,一次用于“停止”的应用程序,一次用于“运行”的应用程序。

希望清楚

提前致谢

编辑:这是我迄今为止尝试过的:

{% if application.service.status|lower == "enabled" %} 
<div>...display running HTML...</div>
{% else %}
<div>...display the non-runing HTML..</div>
{% endif %}

我只想知道我做的是否正确(DRY?)

【问题讨论】:

  • 你熟悉django模板语法和基本标签吗?看起来知道基本标签 {% for %} 和 {% if %} 就足够了。
  • 谢谢,我已编辑问题以回答您的问题。听起来对吗?
  • 是的,100% 没问题,模板通常充满了类似的方案:)

标签: python django django-templates


【解决方案1】:

你提出的建议很干。

{% if application.service.status|lower == "enabled" %} 
<div>...display running HTML...</div>
{% else %}
<div>...display the non-runing HTML..</div>
{% endif %

请记住,您将依赖 return render(request... 来确定 html Django 需求构造。

您提出的解决方案将选择其中之一。 IE。如果您的非运行 HTML 需要切换到运行 HTML,您将无法在没有其他渲染的情况下访问它。

为了更清晰和简洁,django 模板将构建适当的 HTML,而忽略替代选项或“条件”。

如果你学了一点 jQuery,你可以让页面的元素切换当前显示的 html。将此扩展到 ajax 将允许您从服务器获取状态更新,反之亦然。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2014-12-06
    • 2011-02-04
    • 2013-04-23
    • 2021-10-08
    • 2020-09-27
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多