【问题标题】:`with` template tag with logical comparison result as value以逻辑比较结果为值的`with`模板标签
【发布时间】:2018-05-11 13:11:18
【问题描述】:

有没有办法将比较中的逻辑值分配给当前上下文中的变量?

我试过了:

{% with hidden=forloop.counter > 4 %}
  {% include "path/to/template.html" %}
{% endwith %}

它不起作用,因为这会导致语法错误。但也许只是一种我不知道的语法?

到目前为止,我做了这样的事情:

{% if forloop.counter > 4 %}
  {% with hidden=True %}
    {% include "path/to/template.html" %}
  {% endwith %}
{% else %}
  {% include "path/to/template.html" %}
{% endif %}

而且它有效,但对我来说它看起来很脏。

【问题讨论】:

    标签: django templates with-statement


    【解决方案1】:

    include 模板标签allows you to pass extra context

    {% if forloop.counter > 4 %}
      {% include "path/to/template.html" with hidden=True %}
    {% else %}
      {% include "path/to/template.html" %}
    {% endif %}
    

    【讨论】:

    • 确实如此,而且更简单。但是您能否直接以某种方式将比较步骤放在包含标签中? (还有更多)
    • 您如何在包含的模板中使用“隐藏”?您可以将计数传递给包含的模板“with count=forloop.counter”
    • 我将它用作布尔值,以便向包含的模板中的元素添加或不添加类。但是如果没有办法将比较步骤放在标签参数中,我会坚持使用 if/else 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 2018-05-14
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多