Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

jinja2

I would like to do something like:

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

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

result output is:
1 2 3 4

like image 959
user422100 Avatar asked Sep 24 '11 06:09

user422100


1 Answers

You could use loop.index:

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

Check the template designer documentation.

In more recent versions, due to scoping rules, the following would not work:

{% set count = 1 %} {% for i in p %}   {{ count }}   {% set count = count + 1 %} {% endfor %} 
like image 160
zeekay Avatar answered Sep 30 '22 11:09

zeekay