Templating
We're playing the role of a cheese enthusiast
who wants to build a site to:
We created three views + templates:
<html>
<head>
<title>Cheeses We Have</title>
</head>
<body>
<h1>Cheeses We Have</h1>
<ul>
{% for slug, name, country in cheeses %}
<li>
<a href="{% url 'cheese_detail' slug %}">{{ name }}</a>, from {{ country }}
</li>
{% endfor %}
</ul>
</body>
</html>
Templates:
An example context:
context = {
"first_name": "Sally",
"last_name": "Smith,
"age": 35
}
...and its accompanying template:
{{ first_name }} {{ last_name }} is {{ age }} years old.
{% if user.is_active %}
Hello, active user.
{% else %}
Your user is no longer active.
{% endif %}
{% if user.age < 18 %}
This user is not an adult.
{% else %}
This user is an adult.
{% endif %}
{% if user.is_active and user.age >= 18 %}
This active user is an adult.
{% endif %}
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% empty %}
<li>No users found.</li>
{% endfor %}
</ul>
{% for key, value in some_dictionary.items() %}
{{ key }} #{{ forloop.counter }} is {{ value }}
{% endfor %}
{{ name|lower }}
.
{{ name }}
variable after being filtered through the lower filter, which converts text to lowercase.{{ value|default:"nothing" }}
displays the value
or a default if it's None
.{{ value|length }}
displays the length of value
.{{ value|date:"Y-M-D" }}
formats a date/datetime object{{ value|first }}
prints the first thing in a list {{ value|last }}
does the opposite{{ value|floatformat }}
rounds a floating-point number. Here's an example base.html
file
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>{% block title %}Cheese Shop{% endblock %}</title>
</head>
<body>
<h1 class="logo">The Cheese Shop</h1>
<div id="navigation">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/cheeses/">Cheeses</a></li>
</ul>
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
A child template for an individual
cheese detail page might look like this:
{% extends "base.html" %}
{% block title %}{{ cheese.name }}{% endblock %}
{% block content %}
<h2>{{ cheese.name }}</h2>
<p>Country of origin: {{ cheese.country }}</p>
<p>{{ cheese.description }}</p>
{% endblock %}