How to define and increment value of a variable in django template?

95 views Asked by At

I want to define a variable in a Django template and then increment its value by 1.

{% with variable=0 %}
            {% if some_condition == True %}
                {{ variable++ }}
            {% endif %}
{% endwith %}

For defining the variable, I have figured out that I can use with. How can I increment its value?

1

There are 1 answers

0
willeM_ Van Onsem On

Please don't. Business logic does not belong in the template. Django's template language is deliberately restricted to make such things perhaps not impossible, but at least very inconvenient.

The template language thus aims to make it very hard to update variables, since variable that change a value are less predictable and thus prone to errors.

This belongs in the view: the view should make the right queries and pass the data to the template in an accessible way to do this.

Finally Django's template language is slow, it implies a lot of function calls and context resolution, so doing this in a template would also slow down the process quite effectively.

How can I increment its value?

Not easily, one could make a custom template tag for example to do this, but that would be a very bad idea. The reason the template language has no easy template tags to do this, is because it would be bad code design.