[Fixed]-Django Template – New Variable Declaration

21👍

Check out the documentation on the for loop.

It automatically creates a variable called forloop.counter that holds the current iteration index.

As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the add filter. Likewise, you can create your own filters just like with tags.

6👍

If you want to set any variable inside a Django template, you can use this small template tag I’ve written.

3👍

this is how to do it:

{% with name="World" greeting="Hello" %}     
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}

see also: with tag

by john and yarden from this post:
How to set a value of a variable inside a template code?

2👍

In template:

{% for outer_obj in outer_list %}
    {% for inner_obj in inner_list %}
         {% increment_counter forloop.counter0 forloop.parentloop.counter0 outer_list.count %}
    {% endfor %}
 {% endfor %}

Templatetag:

@register.simple_tag
def increment_counter(outer, inner, outer_loop_length):
    return outer + inner * outer_loop_length + inner * (outer_loop_length - 1)

Result: 0 1 2 3 …

Leave a comment