Template Language

Output variables with {{ }} and add logic with {% %} tags.

Syntax{{ value|filter }} and {% tag %}

The Django Template Language has two core constructs:

  • {{ variable }} — prints a value (auto-escaped for safety).
  • {% tag %} — runs logic like loops and conditionals.

You can walk into attributes and dictionary keys with a dot: {{ post.title }}. Filters transform output using a pipe: {{ name|upper }}.

Example

Example · python
<h1>{{ title }}</h1>

<ul>
{% for post in posts %}
    <li>{{ post.title|upper }} &mdash; {{ post.created|date:"Y-m-d" }}</li>
{% empty %}
    <li>No posts yet.</li>
{% endfor %}

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% endif %}

When to use it

  • A developer uses the {{ post.title|upper }} filter to display a blog title in uppercase without editing Python code.
  • A template uses the {% if user.is_authenticated %} tag to show different navigation links for logged-in users.
  • A developer loops over a queryset with {% for product in products %} to render a product grid automatically.

More examples

Variable output and filters

Uses built-in filters to format a title, truncate body text, and format a date in one template.

Example · html
<h1>{{ article.title|title }}</h1>
<p>{{ article.body|truncatewords:50 }}</p>
<small>{{ article.published|date:"M d, Y" }}</small>

Conditional and loop tags

Combines {% if %} and {% for %} tags to conditionally render a list of products.

Example · html
{% if products %}
  <ul>
  {% for product in products %}
    <li>{{ product.name }} - ${{ product.price }}</li>
  {% endfor %}
  </ul>
{% else %}
  <p>No products found.</p>
{% endif %}

URL tag and comment

Uses the {% url %} tag to build a safe URL from a named pattern and a template comment.

Example · html
{# This link goes to the post detail page #}
<a href="{% url 'blog:post-detail' post.pk %}">
  {{ post.title }}
</a>

Discussion

  • Be the first to comment on this lesson.