← Django tutorial

Django

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.

Example
{# 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>
Output
Renders a bulleted list of every post's title, or "No posts yet." if the posts list is empty.
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account