LOGBOOK

HELP

Quiz Entry - updated: 2026.12.01

How do you write a loop in a Jinja2 template, and what is loop.index?

{% for user in users %} ... {% endfor %} repeats the enclosed text once per element; inside the loop, loop.index is the current iteration number, starting at 1.

{% for user in users %}
      {{ user }}
{% endfor %}

With users: [alice, bob], this writes one line per user. The text between the tags is the "body"; anything in it, including the indentation, is repeated.

Jinja2 provides a loop variable inside every for:

Variable Value
loop.index 1, 2, 3, ... (counts from 1)
loop.index0 0, 1, 2, ... (counts from 0)
loop.first / loop.last true on the first / last pass
loop.length number of items

loop.last is handy for separators: {{ user }}{% if not loop.last %},{% endif %} writes alice,bob without a trailing comma.

Go deeper:

From Quiz: ITIA / Ansible: Managing Files and Jinja2 Templates | Updated: Dec 01, 2026