Menu
CoddyTech

Loops in Templates

Part of the Django Basics section of Coddy's Django journey. Lesson 13 of 23.

The café has a new page, /drinks/. Its view passes every drink to the template as drinks, but the list on the page is empty. The {% for %} tag repeats HTML once per item. A page listing free tables:

<ul>
{% for table in free_tables %}
    <li>Table {{ table }} is free.</li>
{% empty %}
    <li>Every table is taken.</li>
{% endfor %}
</ul>

It works like Python's for, with table set to each item in turn. Templates have no indentation rules, so {% endfor %} closes the loop. The optional {% empty %} part shows only when the list has nothing in it.

The loop sees only names in the context, like drinks, not the variables of views.py.

challenge icon

Challenge

Easy

In drinks.html, loop over drinks inside the <ul>:

  • one <li class="drink"> per drink, with its name;
  • when there are no drinks, <li>No drinks today.</li> instead.

Press Run: /drinks/ lists four drinks.

Try it yourself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Our Drinks</title>
</head>
<body>
    <h1>Our Drinks</h1>
    <ul>
        <!-- one <li class="drink"> per drink -->
    </ul>
</body>
</html>

All lessons in Django Basics

Practice on your own: Django playground