SyntaxStudy
Sign Up
Django Django Template Language Basics
Django Beginner 1 min read

Django Template Language Basics

Django's template language (DTL) provides a concise syntax for generating HTML dynamically. Variables are enclosed in double curly braces: {{ variable }}. Template tags, which control logic, are enclosed in {% %} blocks. The template engine safely escapes HTML in variables by default, preventing cross-site scripting (XSS) attacks without any extra effort. The most common template tags are {% if %}, {% for %}, {% url %}, {% block %}, {% extends %}, and {% include %}. The {% if %} tag supports elif and else branches as well as boolean operators (and, or, not) and comparison operators. The {% for %} loop exposes a forloop variable with attributes like forloop.counter, forloop.first, and forloop.last which are useful for adding CSS classes or separators. Filters modify variable values before display and are applied with the pipe character: {{ value|filter }}. Common filters include date (format a datetime), truncatewords (limit to N words), lower and upper (change case), default (fallback value), linebreaks (convert newlines to HTML), and length (count items). Filters can be chained: {{ text|lower|truncatewords:20 }}.
Example
{# templates/blog/post_list.html #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog Posts</title>
</head>
<body>

<h1>Latest Posts</h1>

{% if posts %}
    <ul class="post-list">
    {% for post in posts %}
        <li class="post-item {% if forloop.first %}first{% endif %}">
            <h2>
                <a href="{% url 'post-detail' pk=post.pk %}">
                    {{ post.title }}
                </a>
            </h2>
            <p class="meta">
                By {{ post.author.get_full_name|default:post.author.username }}
                on {{ post.published_at|date:"N j, Y" }}
            </p>
            <p>{{ post.body|truncatewords:30 }}</p>
        </li>
        {% if not forloop.last %}<hr>{% endif %}
    {% endfor %}
    </ul>
{% else %}
    <p>No posts found.</p>
{% endif %}

{# Pagination #}
{% if page_obj.has_other_pages %}
    <nav>
        {% if page_obj.has_previous %}
            <a href="?page={{ page_obj.previous_page_number }}">Previous</a>
        {% endif %}
        <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">Next</a>
        {% endif %}
    </nav>
{% endif %}

</body>
</html>