Menu
CoddyTech

Template Filters

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

The drinks list should say how many drinks there are and show prices like $3.50, but {{ drink.price }} prints 3.5. A filter changes a value as the template prints it. It follows a |, and some take an argument after a colon:

{{ guest.name|upper }}         {# ADA #}
{{ rating|floatformat:1 }}     {# 4.7, when rating is 4.66 #}
{{ boxes|length }} box{{ boxes|pluralize:"es" }}
{# ... #} is a template comment, never shown. floatformat's argument is how many decimals it always shows. length counts a list's items, and pluralize adds an ending, s unless you give another, when the count is not exactly one: 3 boxes, 1 box.

Filters change only what is printed, never the data in your view.

challenge icon

Challenge

Easy

In drinks.html:

  • under the <h1>, a <p class="count"> that says 4 drinks, or 1 drink when there is one;
  • in each drink's <li>, after the name, a <span class="price"> with two decimals: $3.50.

Press Run and look at /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>
        {% for drink in drinks %}
            <li class="drink">
                {{ drink.name }}
                {% if drink.sold_out %}
                    <span class="sold-out">Sold out</span>
                {% endif %}
            </li>
        {% empty %}
            <li>No drinks today.</li>
        {% endfor %}
    </ul>
</body>
</html>

All lessons in Django Basics

Practice on your own: Django playground