Skip to content

Looping in Your Template

Printing {{ people }} showed the whole list as one blob of text. That is not useful. What you want is to go through the list one item at a time and display each person neatly.

In Python you would write a for loop. In Jinja2 you do the same thing — just with a slightly different look.


The Jinja2 for loop

{% for person in people %}
    <p>{{ person.name }}</p>
{% endfor %}

Compare that to Python:

for person in people:
    print(person["name"])

Same idea. The differences: - {% %} wraps the loop line instead of a colon - You need {% endfor %} to close it — HTML has no indentation to rely on - You access dictionary keys with a dot: person.name instead of person["name"]

Everything between {% for %} and {% endfor %} repeats for each item in the list.


Accessing each field

Each item in people is a dictionary with three keys: name, age, gender.

{% for person in people %}
    <p>{{ person.name }} — {{ person.age }} years old</p>
{% endfor %}

That prints one line per person. Run it and you should see:

Alice — 24 years old
Bob — 31 years old
Carol — 19 years old

Handling gender

The gender is stored as 1 or 2. You probably want to show "Male" or "Female" instead of a number. Jinja2 has if statements too:

{% for person in people %}
    <p>
        {{ person.name }},
        {{ person.age }} years old,
        {% if person.gender == 1 %}Male{% else %}Female{% endif %}
    </p>
{% endfor %}
  • {% if %} checks a condition
  • {% else %} handles the other case
  • {% endif %} closes it

Again — same logic as Python, just wrapped in {% %} and closed explicitly.


Your full index.html so far

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>People</title>
  </head>
  <body>

    <h1>People</h1>

    {% for person in people %}
      <p>
        {{ person.name }},
        {{ person.age }} years old,
        {% if person.gender == 1 %}Male{% else %}Female{% endif %}
      </p>
    {% endfor %}

  </body>
</html>

Challenge

Update your index.html with the loop above. Run the app and confirm all three people appear on the page with their name, age, and gender shown as Male or Female.

Then add a fourth person to the people list in app.py — save, refresh, and watch them appear automatically. You did not touch the HTML. The loop handled it.


← Passing Data to Your Template    Next: Displaying a Table →