如何有条件地在 Django 中应用模板过滤器?

How to conditionally apply a template filter in Django?

假设我有一个 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>

建议?

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

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