Skip to content

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:

  1. Variables:
  2. Tags: {% tag %}
  3. 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.

html
<!-- 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 uppercase
  • lower: Convert to lowercase
  • truncatewords: Truncate words
  • floatformat: Format floating point numbers
  • date: Format dates
  • default: Set default value

Tag Usage

Django template tags use {% %} syntax to control logic flow.

html
<!-- 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:

html
<!-- 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:

  1. ✅ Template syntax consists of three elements: variables, tags, and comments
  2. ✅ Variables use syntax and support filter processing
  3. ✅ Tags use {% tag %} syntax to control template logic flow
  4. ✅ Comments are divided into HTML comments and Django template comments
  5. ✅ 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.

7.2 Template Inheritance →

Contents

Back to Course Outline

Released under the [BY-NC-ND License](https://creativecommons.org/licenses/by-nc-nd/4.0/deed.en).