How to increment a variable in a for loop in jinja template?

I would like to do something like:

the variable p is from test.py, which is a list of ['a', 'b', 'c', 'd']

{% for i in p %} {{variable++}} {{variable}} 

output: 1 2 3 4

+46
python jinja2
Sep 24 '11 at 6:31
source share
4 answers

You can use set to increment the counter:

 {% set count = 1 %} {% for i in p %} {{ count }} {% set count = count + 1 %} {% endfor %} 

Or you can use loop.index :

 {% for i in p %} {{ loop.index }} {% endfor %} 

Check out the template constructor .

+81
Sep 24 2018-11-11T00:
source share

According to Jeroen, there are problems with defining the scope: if you set "count" outside the loop, you cannot change it inside the loop.

You can defeat this behavior by using an object, rather than a scalar for "count":

 {% set count = [1] %} 

Now you can manipulate the account inside forloop or even% include%. This is how I increase the score (yes, this is kludgy, but good):

 {% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #} 
+35
Sep 21 '15 at 17:12
source share

Here is my solution:

Put all the counters in the dictionary:

 {% set counter = { 'something1': 0, 'something2': 0, 'etc': 0, } %} 

Define a macro to enlarge it easily:

 {% macro increment(dct, key, inc=1)%} {% if dct.update({key: dct[key] + inc}) %} {% endif %} {% endmacro %} 

Now that you want to increment the "something1" counter, simply do:

 {{ increment(counter, 'something1') }} 
+1
Aug 11 '17 at 20:06 on
source share

Came searching for a Django method for this and found this post. Maybe someone else will need the django solution that comes here.

 {% for item in item_list %} {{ forloop.counter }} {# starting index 1 #} {{ forloop.counter0 }} {# starting index 0 #} {# do your stuff #} {% endfor %} 

More details here: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/

-2
Jul 24 '17 at 6:32
source share



All Articles