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

PythonJinja2

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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 %}

Solution 2 - Python

After 2.10, to solve the scope problem, you can do something like this:

{% set count = namespace(value=0) %}
{% for i in p %}
  {{ count.value }}
  {% set count.value = count.value + 1 %}
{% endfor %}

Solution 3 - Python

As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

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

{% set count = [1] %}

You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}

Or...
{% set count = [] %}
{% for something-that-loops %}
   {% set __ = count.append(1) %} 
   <div> Lorem ipsum meepzip dolor...
   {{ count|length }}
   </div>
{% endfor %}

(From comments by @eyettea and @PYB)

Solution 4 - Python

Here's my solution:

Put all the counters in a dictionary:

{% set counter = {
    'counter1': 0,
    'counter2': 0,
    'etc': 0,
    } %}

Define a macro to increment them easily:

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

Now, whenever you want to increment the 'counter1' counter, just do:

{{ increment(counter, 'counter1') }}

Solution 5 - Python

if anyone want to add a value inside loop then you can use this its working 100%

{% set ftotal= {'total': 0} %} 
{%- for pe in payment_entry -%}
    {% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %} 
{%- endfor -%}

{{ftotal.total}}

output = 5

Solution 6 - Python

Came searching for Django's way of doing this and found this post. Maybe someone else need the django solution who come here.

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

    {# do your stuff #}
{% endfor %}

Read more here: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/

Solution 7 - Python

I was struggle with this behavior too. I wanted to change div class in jinja based on counter. I was surprised that pythonic way did not work. Following code was reseting my counter on each iteration, so I had only red class.

{% if sloupec3: %}
	{% set counter = 1 %}
	{% for row in sloupec3: %}
        {% if counter == 3 %}
            {% set counter = 1 %}        
        {% endif %} 
		
		{% if  counter == 1: %}
	       <div class="red"> some red div </div>
		{% endif %}	
	
    	{% if counter == 2: %}
	       <div class="gray"> some gray div </div>
		{% endif %}	
        
        {% set counter = counter + 1 %}	

	{% endfor %}

{% endif %}

I used loop.index like this and it works:

{% if sloupec3: %}
 
	{% for row in sloupec3: %} 
		
		{% if  loop.index % 2 == 1: %}
	       <div class="red"> some red div </div>
		{% endif %}	
	
    	{% if loop.index % 2 == 0: %}
	       <div class="gray"> some gray div </div>
		{% endif %}	 
        
	{% endfor %}

{% endif %}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser422100View Question on Stackoverflow
Solution 1 - PythonzeekayView Answer on Stackoverflow
Solution 2 - PythonPatrick José PereiraView Answer on Stackoverflow
Solution 3 - PythonPeter HollingsworthView Answer on Stackoverflow
Solution 4 - PythonJahidView Answer on Stackoverflow
Solution 5 - Pythonpratik soniView Answer on Stackoverflow
Solution 6 - PythonTuxedo JoeView Answer on Stackoverflow
Solution 7 - PythonTomRavnView Answer on Stackoverflow