Loops

Jinja provides two types of loops. The first one is the for loop:

For

Loop over each item in an array. For example, to display a list of users given user_list:

<ul>
{% for user in user_list %}
  <li><a href="/profile/{{ user.id }}/">{{ user.name }}</a></li>
{% endfor %}
</ul>

You can also loop over a list in reverse by using {% for obj in list reversed %}.

You can also define a {% elsefor %} statement, which gets rendered if the for loop doesn't iterate:

<ul>
{% for user in userlist %}
  <li>{{ user }}</li>
{% elsefor %}
  <li><strong>no user found</strong></li>
{% endfor %}
</ul>

Range

range loops can be used to iterate through a list of numbers:

{% range number from 1 to 10 %}
  {{ number }}
{% endrange %}

You can also step downwards:

{% range number from 10 downto 1 %}
  {{ number }}
{% endrange %}

It is even possible to set the stepsize:

{% range number from 1 to 100 step 33 %}
  {{ number }}
{% endrange %}

Loop Variables

These variables are available inside each for and range loop:

Variable Description
loop.counter The current iteration of the loop
loop.counter0 The current iteration of the loop, starting counting by 0.
loop.revcounter The number of iterations from the end of the loop.
loop.revcounter0 The number of iterations from the end of the loop, starting counting by 0.
loop.first True if first iteration.
loop.last True if last iteration.
loop.even True if current iteration is even.
loop.odd True if current iteration is odd.
loop.parent The context of the parent loop.

Cycling

Cycle among the given strings each time this tag is encountered.

Within a loop, cycles among the given strings each time through the loop:

{% for row in rows %}
  <tr class="{% cycle 'row1', 'row2' inline %}">
    ...
  </tr>
{% endfor %}

Or by cycling into a variable:

{% for row in rows %}
  {% cycle rowclass through "row1", "row2" %}
  <tr>
    <td class="{{ rowclass }}">...</td>
    <td class="{{ rowclass }}">...</td>
    ...
  </tr>
{% endfor %}

IfChanged

Check if a value has changed from the last iteration of a loop.

The 'ifchanged' block tag is used within a loop. It checks its own rendered contents against its previous state and only displays its content if the value has changed:

<h1>Userlist</h1>

{% for user in users %}
{% ifchanged %}<h3>{{ user.type }}</h3>{% endifchanged %}
  {{ user.name }}
{% endfor %}

Recursion

Often it's important to be able to use recursion. For example when you want to build a sitemap or a tree.

In Jinja every for tag can be used to call it again with other variables:

<ul class="sitemap">
{% for item in sitemap %}
  <li><a href="{{ item.link }}">{{ item.title|e }}</a>{%
    if item.items %}<ul>{% recurse item.items %}</ul></li>
{% endfor %}
</ul>

If you want to recurse in a higher loop you can use this syntax:

{% recurse item.items in loop.parent %}