[Fixed]-Advanced Django Template Logic

29👍

The docs for the if template tag say:

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.

This is a cleaner way to express your logic with nested tags:

{% if A %}
  {% if B or C %}
    {{ do stuff }}
  {% endif %}
{% endif %}

6👍

Assign whatever inside the parenthesis to a variable.

{% with B or C as D %}
  {% if A and D %}
    {{ do stuff }}
  {% endif %}
{% endwith %}

PS: This does not work on newer versions.

2👍

Alternatively, you can ‘expand’ the contents of the parenthesis and evaluate it as:

{% if A and B or A and C %}
    {{ do stuff }}
{% endif %}

Leave a comment