Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced Django Template Logic

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 %}
like image 795
Daniel Rosenthal Avatar asked Jul 25 '13 19:07

Daniel Rosenthal


People also ask

What does {{ name }} mean in Django templates?

8. What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

Can you do math in Django template?

Use django-mathfilters. In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value. For the specific example above, you would use {{ 100|sub:object.

What is DTL in Django?

Django Template Language (DTL) is the primary way to generate output from a Django application. You can include DTL tags inside any HTML webpage. The basic DTL tag you can include in an HTML webpage is: 1. {% Tag %}

Is Django template Jinja?

The Django template language doesn't have an equivalent of Jinja2 tests.


2 Answers

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 %}
like image 120
Peter DeGlopper Avatar answered Nov 16 '22 01:11

Peter DeGlopper


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.

like image 40
Vinayak Kaniyarakkal Avatar answered Nov 16 '22 01:11

Vinayak Kaniyarakkal