BudiBadu Logo
Samplebadu

Flask by Example: Template Loop Blocks

Flask 3.0+

Iterating over lists and dictionaries is a fundamental requirement for displaying dynamic content. Jinja2 provides a robust `for` loop with special helper variables.

Code

<!-- templates/users.html -->
<ul>
    {% for user in users %}
        <li class="{{ loop.cycle('odd', 'even') }}">
            <!-- 1. Access loop index (1-based) -->
            <span class="index">{{ loop.index }}.</span>
            
            {{ user.name }}
            
            <!-- 2. Check for first/last iteration -->
            {% if loop.first %} (Leader) {% endif %}
            {% if loop.last %} (Newest) {% endif %}
        </li>
    {% else %}
        <!-- 3. Fallback if list is empty -->
        <li>No users found.</li>
    {% endfor %}
</ul>

<!-- 4. Looping through a dictionary -->
<dl>
    {% for key, value in settings.items() %}
        <dt>{{ key }}</dt>
        <dd>{{ value }}</dd>
    {% endfor %}
</dl>

Explanation

The {% for %} tag allows you to iterate over lists and dictionaries within your templates. Inside the loop, Jinja provides a special loop variable that gives you context, such as the current index (loop.index) or whether it's the first iteration (loop.first).

This eliminates the need for manual counters and simplifies common display logic. You can easily style the first item differently or create alternating row colors using the loop.cycle() helper.

A unique feature of Jinja loops is the {% else %} block. This block executes only if the iterable is empty, providing a clean and readable way to handle "no results found" scenarios without extra if checks.

Code Breakdown

3
loop.cycle('odd', 'even') is a helper that returns 'odd' on the first iteration, 'even' on the second, 'odd' on the third, and so on. It's perfect for striping table rows.
5
loop.index returns the current iteration count starting at 1. Use loop.index0 if you need a 0-based index (like for array access in JavaScript).
13
{% else %} inside a for loop is a Jinja-specific feature. It renders only if users is empty or None.
19
settings.items() iterates over a dictionary, unpacking keys and values just like in Python.