[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 %}
πŸ‘€gdvalderrama

Leave a comment