How to Use For Loop in Jinja2 Templates with Flask
In Flask, you use a
for loop in Jinja2 templates by enclosing the loop inside {% for item in list %} ... {% endfor %} tags. This lets you repeat HTML elements for each item in a list passed from your Flask route.Syntax
The for loop in Jinja2 uses the syntax {% for item in list %} ... {% endfor %}. Here, item is a variable representing the current element, and list is the iterable you want to loop over.
You place the HTML or template code you want repeated inside the loop tags.
jinja2
{% for item in list %}
{{ item }}
{% endfor %}Example
This example shows a Flask app passing a list of fruits to a Jinja2 template. The template uses a for loop to display each fruit in an unordered list.
python + jinja2
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): fruits = ['Apple', 'Banana', 'Cherry'] return render_template('fruits.html', fruits=fruits) # fruits.html template content: # # <ul> # {% for fruit in fruits %} # <li>{{ fruit }}</li> # {% endfor %} # </ul>
Output
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
Common Pitfalls
- Forgetting to close the loop with
{% endfor %}causes template errors. - Using
{{ }}instead of{% %}for the loop tags is incorrect;{{ }}is for expressions, not control flow. - Passing a non-iterable (like None or a single value) to the loop will cause errors or no output.
jinja2
{# Wrong: missing endfor #}
{% for item in items %}
{{ item }}
{# Correct #}
{% for item in items %}
{{ item }}
{% endfor %}Quick Reference
| Usage | Description |
|---|---|
| {% for item in list %} ... {% endfor %} | Loop over each item in a list or iterable |
| {{ item }} | Display the current item inside the loop |
| {% if condition %} ... {% endif %} | Use conditions inside loops for filtering or logic |
| loop.index | Current loop iteration number starting at 1 |
| loop.first | True if this is the first iteration |
| loop.last | True if this is the last iteration |
Key Takeaways
Use {% for item in list %} ... {% endfor %} to loop over lists in Jinja2 templates.
Always close your for loops with {% endfor %} to avoid errors.
Pass iterable data from Flask routes to templates for looping.
Use {{ item }} inside the loop to display each element.
Leverage loop variables like loop.index for extra control inside loops.