Lesson 18 of 60 – Django Template Tags
30%

Django Template Tags

Django Template Tags are special instructions used inside HTML templates to perform logic and other template operations. Unlike template variables, which are mainly used to display values, template tags can control conditions, loops, inheritance, static files, and more.

Note: Django template tags are written using {% %}. For example, {% if user %} starts an if condition in a Django template.

1. What is a Template Tag?

A template tag is a special Django instruction used inside an HTML template. It allows the template to perform an operation or control how content is displayed.

{% if user %}
    <p>Welcome</p>
{% endif %}

2. Template Tag Syntax

Template tags use curly braces with percentage symbols.

{% tag %}

For example:

{% if age >= 18 %}

The closing tag for block tags is usually written separately.

3. Template Tags vs Variables

Variable:

{{ name }}

Template tag:

{% if name %}

Variables generally display values, while template tags perform template operations.

4. The if Tag

The if tag is used to display content when a condition is true.

{% if age >= 18 %}
    <p>You are eligible.</p>
{% endif %}

5. The else Tag

The else section can be used when the if condition is false.

{% if age >= 18 %}
    <p>Adult</p>
{% else %}
    <p>Minor</p>
{% endif %}

6. The elif Tag

Django supports elif for checking multiple conditions.

{% if marks >= 80 %}
    <p>Grade A</p>
{% elif marks >= 60 %}
    <p>Grade B</p>
{% else %}
    <p>Grade C</p>
{% endif %}

7. The for Tag

The for tag is used to repeat HTML content for each item in a collection.

{% for student in students %}
    <p>{{ student }}</p>
{% endfor %}

8. Looping Through a List

View:

def students(request):

    data = {
        'students': [
            'Rahul',
            'Amit',
            'Priya'
        ]
    }

    return render(
        request,
        'students.html',
        data
    )

Template:

{% for student in students %}
    <p>{{ student }}</p>
{% endfor %}

9. Empty for Loop

The empty clause can display a message when a collection contains no items.

{% for student in students %}
    <p>{{ student.name }}</p>
{% empty %}
    <p>No students found.</p>
{% endfor %}

10. The comment Tag

The comment tag can be used for template comments that should not appear in the rendered HTML.

{% comment %}
This content is a Django template comment.
{% endcomment %}

11. The extends Tag

The extends tag is used for template inheritance.

{% extends 'base.html' %}

It allows a child template to reuse the structure of a base template.

12. The block Tag

The block tag defines an area that child templates can replace.

{% block content %}

{% endblock %}

It is commonly used together with extends.

13. Template Inheritance Example

base.html

<html>
<body>

<h1>My Website</h1>

{% block content %}
{% endblock %}

</body>
</html>

home.html

{% extends 'base.html' %}

{% block content %}
    <h2>Home Page</h2>
{% endblock %}

14. The include Tag

The include tag allows one template to include another template.

{% include 'header.html' %}

This is useful for reusable components such as headers, menus, and footers.

15. Including a Footer

<body>

{% include 'header.html' %}

<h1>Home Page</h1>

{% include 'footer.html' %}

</body>

Common page sections can be maintained in separate files.

16. The load Tag

The load tag is used to load template tag libraries.

For example, Django's static template tags can be loaded using:

{% load static %}

17. The static Tag

The static tag is used to generate URLs for static files.

{% load static %}

<link rel="stylesheet"
      href="{% static 'css/style.css' %}">

18. The csrf_token Tag

The csrf_token tag is commonly used inside Django POST forms to include a CSRF token.

<form method="post">

    {% csrf_token %}

    <input type="text" name="name">

    <button type="submit">Submit</button>

</form>

19. The url Tag

The url tag can create a URL using the name of a URL pattern.

{% url 'home' %}

This is useful because templates do not need to hard-code every application URL.

20. URL Tag with Parameters

The url tag can also pass parameters to a named URL.

{% url 'student' student.id %}

This can generate a dynamic URL for a particular student.

21. The with Tag

The with tag creates a simpler variable name for a value inside a specific template block.

{% with full_name=student.name %}
    <h2>{{ full_name }}</h2>
{% endwith %}

22. The firstof Tag

The firstof tag outputs the first variable from a list of variables that evaluates to a non-empty value.

{% firstof username nickname "Guest" %}

If username is empty, Django checks the next value.

23. The cycle Tag

The cycle tag cycles through a list of values each time it is used inside a loop.

{% for student in students %}

    {% cycle 'one' 'two' %}

    {{ student.name }}

{% endfor %}

24. forloop Variables

Django provides special variables while executing a for loop.

{% for student in students %}

    {{ forloop.counter }}.
    {{ student.name }}

{% endfor %}

forloop.counter starts counting from 1.

25. forloop.counter0

The forloop.counter0 variable starts counting from 0.

{% for student in students %}

    {{ forloop.counter0 }} - {{ student.name }}

{% endfor %}

This can be useful when zero-based numbering is required.

26. forloop.first and forloop.last

Django provides forloop.first and forloop.last to identify the first and last iteration of a loop.

{% for student in students %}

    {% if forloop.first %}
        <p>First Student</p>
    {% endif %}

    <p>{{ student.name }}</p>

    {% if forloop.last %}
        <p>Last Student</p>
    {% endif %}

{% endfor %}

27. Combining Multiple Tags

Multiple template tags can be combined to create dynamic pages.

{% if students %}

    {% for student in students %}

        <p>
            {{ forloop.counter }}.
            {{ student.name }}
        </p>

    {% endfor %}

{% else %}

    <p>No students found.</p>

{% endif %}

28. Common Template Tag Mistakes

  • Using {{ }} when a template tag is required
  • Forgetting to close if blocks with {% endif %}
  • Forgetting {% endfor %}
  • Using an incorrect tag name
  • Forgetting {% load static %} when using static template tags
  • Incorrect URL name with the url tag
  • Incorrect template inheritance syntax

29. Complete Template Tags Example

views.py

from django.shortcuts import render

def students(request):

    data = {
        'students': [
            {'name': 'Rahul', 'age': 20},
            {'name': 'Amit', 'age': 22},
            {'name': 'Priya', 'age': 21}
        ]
    }

    return render(
        request,
        'students.html',
        data
    )

students.html

<h1>Student List</h1>

{% if students %}

    {% for student in students %}

        <p>
            {{ forloop.counter }}.
            {{ student.name }}
            - {{ student.age }}
        </p>

    {% endfor %}

{% else %}

    <p>No students found.</p>

{% endif %}

30. Summary of Django Template Tags

Django template tags provide a way to add logic and special operations to HTML templates without placing Python code directly inside the HTML.

  • if checks conditions.
  • for repeats content.
  • extends supports template inheritance.
  • block defines replaceable sections.
  • include reuses another template.
  • load loads template tag libraries.
  • static handles static file URLs.
  • csrf_token is used with Django POST forms.
  • url creates URLs from named URL patterns.
  • with, firstof, and cycle provide additional template functionality.

📌 Key Points

  • Django template tags are written using {% %}.
  • Template tags perform operations inside templates.
  • if, elif, and else control conditions.
  • for is used for loops.
  • extends and block are used for template inheritance.
  • include helps reuse template components.
  • url generates URLs using named URL patterns.
  • static is used for static file URLs.
  • csrf_token is commonly used inside POST forms.

🧠 Quick Quiz

Question: Which syntax is used for Django template tags?