Links Between Pages
Part of the Django Basics section of Coddy's Django journey. Lesson 16 of 23.
Every drink has its page at /drinks/<slug>/, and the list on /drinks/ should link to them. In a template, the {% url %} tag builds an address from a route's name, as reverse() does in a view:
<a href="{% url 'menu:about' %}">About us</a>
<a href="{% url 'menu:table' 7 %}">Table 7</a>The name comes first, in quotes, with its namespace. The converter values follow, separated by spaces, and they can be variables: in a loop, {% url 'menu:table' table.number %} builds each table's address. Each drink in DRINKS now carries its own slug.
A wrong name or value crashes the page with NoReverseMatch, so a broken link shows up while you build the page, not when a visitor clicks it.
Challenge
EasyIn drinks.html, make each drink's name a link to its page: <a href="...">Latte</a> leads to /drinks/latte/. Build the address with {% url %} and the drink's slug.
Press Run and click the Flat White on /drinks/.
Try it yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Our Drinks</title>
</head>
<body>
<h1>Our Drinks</h1>
<p class="count">{{ drinks|length }} drink{{ drinks|pluralize }}</p>
<ul>
{% for drink in drinks %}
<li class="drink">
{{ drink.name }}
<span class="price">${{ drink.price|floatformat:2 }}</span>
{% if drink.sold_out %}
<span class="sold-out">Sold out</span>
{% endif %}
</li>
{% empty %}
<li>No drinks today.</li>
{% endfor %}
</ul>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Django Basics
3Templates
Your First TemplateTemplate VariablesPractice on your own: Django playground