【问题标题】:How to conditionally apply a template filter in Django?如何有条件地在 Django 中应用模板过滤器?
【发布时间】:2021-11-26 02:32:20
【问题描述】:

假设我有一个 Django 模板

<div><b>{{some.long.expression.with.stuff|filter1}}</b></div>

如果my_condition 为真,我只想申请filter1

最好的方法是什么?这是一种带有重复的冗长方式:

{% if my_condition %}
<div><b>{{some.long.expression.with.stuff|filter1}}</b></div>
{% else %}
<div><b>{{some.long.expression.with.stuff}}</b></div>
{% endif %}

这里稍微不那么冗长,更难阅读,仍然有一些重复:

<div><b>{% if my_condition %}{{some.long.expression.with.stuff|filter1}}{% else %}{{some.long.expression.with.stuff}}{% endif %}</b></div>

建议?

【问题讨论】:

    标签: django django-templates django-template-filters


    【解决方案1】:

    您可以使用{% with … %} … {% endwith %} template tag

    {% with somevar=some.long.expression.with.stuff %}
    <div><b>{% if my_condition %}{{ somevar|filter1 }}{% else %}{{ somevar }}{% endif %}</b></div>
    {% endwith %}

    【讨论】:

      猜你喜欢
      • 2015-03-07
      • 1970-01-01
      • 2011-10-03
      • 2021-04-14
      • 2019-09-30
      • 2020-04-23
      • 2015-03-01
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多