Search code examples
djangodjango-templatesdjango-template-filters

How to conditionally apply a template filter in Django?


Suppose I have a Django template with

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

and I only wish to apply filter1 if my_condition is True.

What is the best way? Here is a verbose way with repetition:

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

Here is slightly less verbose, harder to read, still with some repetition:

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

Suggestions?


Solution

  • You can work with a {% with … %} … {% endwith %} template tag:

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