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:
{{ 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
EasyIn drinks.html, under the <h1>, add a <p class="count"> that says 4 drinks, or 1 drink when there is one. In each drink's <li>, after the name, add a <span class="price"> with two decimals, like $3.50.
Open /drinks/: it says 4 drinks, and the Latte costs $3.50.
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
3Templates
Your First TemplateTemplate VariablesPractice on your own: Django playground