Templates
A Django template is an HTML file with special tags:
{{ variable }} prints a value, and {% tag %}
handles logic like loops and conditionals.
Example: looping and handling the empty case
{# blog/post_list.html #}
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% empty %}
<li>No posts yet.</li>
{% endfor %}
</ul>
Renders a bulleted list of every post's title, or "No posts yet."
if the posts list is empty.
The view's context dictionary (that {'posts': posts} from
the Views lesson) is exactly what fills these placeholders in —
{{ post.title }} reads the title attribute off
each Post object the view passed in. {% empty %}
is a small but genuinely useful detail — it renders only when the loop
had nothing to iterate over at all, sparing you from writing a separate
{% if %} just to handle an empty list gracefully.
{# blog/post_list.html #}
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% empty %}
<li>No posts yet.</li>
{% endfor %}
</ul>
Renders a bulleted list of every post's title, or "No posts yet." if the posts list is empty.