Menu
CoddyTech

Conditions in Templates

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

The hot chocolate machine is broken. Each drink now has a "sold_out" value, True or False, and the list should mark the drinks you cannot order.

The {% if %} tag shows its part only when its condition is true. A list of tables:

{% for table in tables %}
    <li>
        Table {{ table.number }}:
        {% if table.free %}Free{% else %}Taken{% endif %}
    </li>
{% endfor %}

Like Python's if, it can have {% elif %} and {% else %}, compares with ==, <, and, or and not, and ends with {% endif %}. Inside a loop, read the item's values through the loop's name: table.free. A bare free is not in the context, counts as false, and its part never shows.

challenge icon

Challenge

Easy

In drinks.html, inside each <li class="drink"> and after the name, add <span class="sold-out">Sold out</span> only when that drink is sold out.

Press Run: on /drinks/, only the Hot Chocolate says Sold out.

Try it yourself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Our Drinks</title>
</head>
<body>
    <h1>Our Drinks</h1>
    <ul>
        {% for drink in drinks %}
            <li class="drink">{{ drink.name }}</li>
        {% empty %}
            <li>No drinks today.</li>
        {% endfor %}
    </ul>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Django Basics

Practice on your own: Django playground