Django Template Tags
Template tags use the {% %} syntax to add logic — loops, conditionals, includes, and more — to otherwise logic-light Django templates.
Tags vs. Variables
A variable tag ({{ }}) outputs a value; a template tag ({% %}) performs an action — looping, branching, loading a tag library, or pulling in another template. Many tags, like if and for, wrap a block of content and must be explicitly closed with an end tag; others, like include and csrf_token, are single, self-contained statements.
Template Inheritance: extends and block
Template inheritance lets a base template define the overall page skeleton once, with named block sections that child templates override. This keeps headers, navigation, and footers in one file instead of copy-pasted across every page.
Example
<!-- base.html -->
<!DOCTYPE html>
<html>
<head><title>{% block title %}My Site{% endblock %}</title></head>
<body>
<header>Site Header</header>
{% block content %}{% endblock %}
</body>
</html>
<!-- home.html -->
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}Including and Linking: include and url
The include tag renders another template in place, which is ideal for repeated snippets like a navigation bar or a product card. The url tag looks up a path by the name given in urls.py, so templates never hardcode a URL that might later change.
Example
<!-- home.html -->
{% include 'partials/navbar.html' %}
<a href="{% url 'article-detail' article.id %}">Read more</a>Example
{% load static %}
<link rel="stylesheet" href="{% static 'css/site.css' %}">
<form method="post">
{% csrf_token %}
<input type="text" name="query">
<button type="submit">Search</button>
</form>- {% if %} / {% elif %} / {% else %} / {% endif %} — conditional branching
- {% for %} / {% empty %} / {% endfor %} — looping over a queryset or list
- {% block %} / {% endblock %} — a named, overridable section of a template
- {% extends %} — inherit the structure of a parent template
- {% include %} — render another template in place
- {% url %} — reverse a URL by its name
- {% csrf_token %} — required inside every POST form
- {% load %} — import a custom tag or filter library, like static
Exercise: Django Template Tags
Which syntax denotes a Django template tag used for logic like loops or conditionals?