Advanced Django Template Logic Advanced Django Template Logic django django

Advanced Django Template Logic


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 %}


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.


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

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