Explain Codes LogoExplain Codes Logo

How to output loop.counter in python jinja template?

python
jinja
template-engineering
loop-control
Anton ShumikhinbyAnton Shumikhin·Feb 19, 2025
TLDR

To showcase a counter in a Jinja loop, you want to employ loop.index for a count that begins at 1, or loop.index0 if you're starting from 0:

{% for item in sequence %} {{ loop.index }}: {{ item }} {% endfor %}

Remember to substitute loop.index with loop.index0 if you prefer zero-based indexing.

Expanding Jinja loop insights for cleaner templates

Downsizing with loop.revindex

Fancy reverse counting? Call on loop.revindex. It's like counting backwards from an event you're not looking forward to:

{% for item in sequence %} {{ loop.revindex }}: {{ item }} // Like countdown to dentist appointment {% endfor %}

Are we there yet?: Tracking loop progression

With the handy loop.first and loop.last, Jinja makes it easy to pinpoint the start and end of a loop—you won't need bread crumbs:

{% for user in users %} {% if loop.first %} First in line: {{ user.name }}! // VIP status guaranteed {% elif loop.last %} Last but not least: {{ user.name }}. // Saving best for last {% else %} Next up: {{ user.name }} {% endif %} {% endfor %}

Jinja templates: now featuring concatenation

Use loop.index0 for string concatenation to generate IDs dynamically. Simple, and no magic required:

{% for item in items %} <div id="item-{{ loop.index0 }}"> Content </div> {% endfor %}

Level up: Manipulate variables within your loops

Jinja's set: The spy within your loop

set allows you to define or modify variables incognito, within the loop itself. Sly, right?

{% for item in items %} {% set new_item = item|upper %} {{ loop.index }} - {{ new_item }} // All uppercase. No shouting, promise. {% endfor %}

Django vs Jinja: Apples and oranges

Hold up! Don't confuse the Django forloop.counter with Jinja's loop counters. They're not alter egos despite the deceptive similarity.

Example guide: Harnessing conditionals in a loop

Conditional expressions offer your Jinja loops the springboard they need to execute complex logic:

{% for number in numbers %} {{ 'Even' if number % 2 == 0 else 'Odd' }} // Sorting out the odds...and evens. {% endfor %}

The ABCs of Jinja control statements

Our Jinja toolkit extends beyond loops. Let's dove deeper, explore control statements, and strum some impressive Jinja guitar chords:

{% for user in users %} {{ user.name }} {% if user.has_error %} {{ user.error_message }} // Whoops, looks like an error... {% break %} // Time to bail! {% endif %} {% endfor %}

Loop-ception: Mastering nested loops

Nested loops can twist your brain. Breathe easy, Jinja’s loop.parentloop can save the day:

{% for category in categories %} {{ category.name }}: {% for product in category.products %} - {{ loop.parentloop.index }}.{{ loop.index }} {{ product.name }} // Loop-ception level: Expert {% endfor %} {% endfor %}