Advanced Django Template Logic

Daniel Rosenthal picture Daniel Rosenthal · Jul 25, 2013 · Viewed 11.3k times · Source

I'm not sure if this is really easy and I just glanced over it in the documentation, or if this is a limitation of the Django template system, but I need to be able to do a little (not very) advanced logic in Django, and I'd rather not have to repeat myself all over.

Let's say I have 3 boolean values; A, B, and C.

I basically need to do:

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

However Django doesn't seem to allow grouping the (B or C) logic with parentheses. Is there a way to do that kind of grouping in Django's template language? Or do I need to do the un-DRY version of that, which would be:

  {% if A and B %}
        {{ do stuff }}
  {% else %}
      {% if A and C %}
          {{ do the same stuff }}
      {% endif %}
  {% endif %}

Answer

Peter DeGlopper picture Peter DeGlopper · Jul 25, 2013

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