Chapter 7: Template System
7.1 Template Basics
Template Syntax
Django Template Language (DTL) is a simple language used in the Django framework to generate HTML. It allows developers to separate Python code logic from HTML markup, enabling parallel development of frontend and backend.
Basic template syntax consists of three main elements:
- Variables:
- Tags:
{% tag %} - Comments:
{# comment #}
Variables and Filters
Variables in templates are represented with double curly braces, like . When the template engine encounters a variable, it replaces it with the variable's value.
<!-- Basic variable usage -->
<h1>{{ title }}</h1>
<p>Author: {{ author.name }}</p>
<p>Publication Date: {{ publish_date }}</p>
<!-- Using filters -->
<p>Title (uppercase): {{ title|upper }}</p>
<p>Article excerpt: {{ content|truncatewords:30 }}</p>
<p>Price: {{ price|floatformat:2 }}</p>Common filters include:
upper: Convert to uppercaselower: Convert to lowercasetruncatewords: Truncate wordsfloatformat: Format floating point numbersdate: Format datesdefault: Set default value
Tag Usage
Django template tags use {% %} syntax to control logic flow.
<!-- Conditional tags -->
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
<!-- Loop tags -->
<ul>
{% for article in articles %}
<li>
<a href="{{ article.get_absolute_url }}">{{ article.title }}</a>
<span>Published on: {{ article.publish_date|date:"Y-m-d" }}</span>
</li>
{% empty %}
<li>No articles available.</li>
{% endfor %}
</ul>
<!-- Include other templates -->
{% include "header.html" %}
<!-- URL reverse resolution -->
<a href="{% url 'article_detail' article.pk %}">Read more</a>Comments
There are two ways to add comments in templates:
<!-- This is an HTML comment, visible in the browser -->
{# This is a Django template comment, not visible in the browser #}
{% comment %}
This is a multi-line comment
Can span multiple lines
Not visible in the browser
{% endcomment %}Template comments are not sent to the client browser, while HTML comments are sent to the browser but not displayed.
Summary
Django template basics are an important part of frontend development:
- ✅ Template syntax consists of three elements: variables, tags, and comments
- ✅ Variables use
syntax and support filter processing - ✅ Tags use
{% tag %}syntax to control template logic flow - ✅ Comments are divided into HTML comments and Django template comments
- ✅ Filters can format variables
Mastering basic template syntax is the prerequisite for using the Django template system.
Next
We will learn about template inheritance mechanisms.