Reading — step 1 of 5
Read
~1 min readControl Flow
Loops & Iteration
{% for item in items %}
- {{ item }}
{% endfor %}
Render the body for each item, with item bound to the loop var.
python
Loop variables (loop namespace in Jinja2):
loop.index: 1-based.loop.index0: 0-based.loop.first,loop.last: booleans.loop.length: total items.loop.cycle('a','b'): cycle through values.
{% for user in users %}
{{ loop.index }}. {{ user.name }}
{% endfor %}
Renders:
1. Alice
2. Bob
3. Carol
Else clause for empty:
{% for item in items %}
{{ item }}
{% else %}
No items.
{% endfor %}
Renders else branch only if iterable was empty.
Nested loops:
- Inner loop's
loopvariable shadows outer. - Access outer via
loop.outer.index(Jinja2 syntax varies).
Iterables:
- Lists, tuples.
- Dicts: iterate keys; or
(key, value)viafor k, v in d.items(). - Strings: iterate chars.
- Custom: any iterable.
Iteration over expensive sequences: lazy generators don't always work. Some engines materialize.
Performance: loops in templates over large datasets are slow. Pre-compute in code.
Break/continue: not in standard Jinja2. Some engines have. Conditional emit instead:
{% for i in items %}
{% if i > 10 %}{{ i }}{% endif %}
{% endfor %}
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…