Back to Web Development
2026-03-257 min read

Tags (Web Development)

Learn Tags (Web Development) step by step with clear examples and exercises.

Title: Django Template Tags - Master Web Development with Practical Depth

Why This Matters

Django is a popular web framework for Python developers, and its template tags are essential for creating dynamic and interactive web pages. Understanding these tags can help you build complex applications more efficiently, saving you time and effort. Furthermore, mastering Django's template tags will make you stand out in job interviews and help you tackle real-world coding challenges.

Prerequisites

To follow this tutorial, you should have a basic understanding of Python programming and familiarity with HTML and CSS. Additionally, you should be comfortable working with the Django web framework and have set up a Django project. If you're new to Django, consider checking out our Django for Beginners tutorial first.

Core Concept

Django template tags are Python functions that can be used within Django templates to generate dynamic content. They allow you to perform various tasks, such as rendering loops, including snippets of other templates, and accessing variables from the view context. In this section, we will explore some common Django template tags and provide examples of how to use them in your projects.

Built-in Template Tags

Django provides a set of built-in template tags that you can use without needing to write any custom code. Here are some essential built-in template tags:

  1. {% for %} and {% endfor %} - Loops through a list or queryset
  2. {% if %} and {% else %} - Conditional statements
  3. {% with %} and {% endwith %} - Temporarily assigns a variable within the block
  4. {% url %} - Generates a URL for a given view name
  5. {% load %} - Loads a template tag library
  6. {% include %} - Includes another template file
  7. {% block %} and {% endblock %} - Defines or overrides a block in the base template

Custom Template Tags

In addition to built-in tags, you can create your own custom template tags by writing Python functions and registering them with Django. This allows you to reuse code across multiple templates and make your templates more maintainable. To create a custom template tag, follow these steps:

  1. Create a new Python module in the templatetags directory of your app. For example, if your app is called myapp, create a file named myapp_tags.py.
  2. Define your template tag as a Python function that takes the request object and a list of arguments (if any). The function should return a string or a template variable.
  3. Register your custom template tag by calling the register decorator from Django's template module at the beginning of your myapp_tags.py file.

Here's an example of a simple custom template tag that returns the current date:

from django import template

register = template.Library()

@register.simple_tag
def current_date():
return template.Context({"current_date": datetime.datetime.now()}).render(template.loader.get_template("base.html"))

Using Template Tags in Your Templates

To use a template tag in your Django templates, simply call the tag by name and pass any necessary arguments within curly braces {% %}. For example:

{% for item in my_list %}
<p>{{ item }}</p>
{% endfor %}

Blocks and Template Inheritance

Django templates support a system of blocks and inheritance, which allows you to create reusable base templates that can be extended by child templates. This is useful for maintaining consistency across your application's templates and reducing redundant code. To define a block in a template, use the {% block %} tag, and to override a block in a child template, use the same tag followed by the name of the block you want to override.

Worked Example

In this example, we will create a simple Django project that displays a list of books using the {% for %} loop and the {% url %} tag.

  1. Create a new Django project:
django-admin startproject my_books
cd my_books
  1. Create an app called books:
python manage.py startapp books
  1. Define the Book model in books/models.py:
from django.db import models

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
publication_date = models.DateField()

def __str__(self):
return self.title
  1. Run migrations to create the database schema:
python manage.py makemigrations books
python manage.py migrate
  1. Create a new superuser:
python manage.py createsuperuser
  1. Define some books in the Django admin site:
python manage.py createsuperuser
(Login to the Django admin site and add some books)
  1. Create a new template tag called book_list that displays a list of books in books/templatetags/books_tags.py:
from django import template
from .models import Book

register = template.Library()

@register.simple_tag
def book_list():
books = Book.objects.all()
return "".join([f"<li><a href='{book.get_absolute_url}'>{book.title}</a></li>" for book in books])
  1. Register the custom template tag:

books/templatetags/books_tags.py

from django import template

register = template.Library()


9. Create a base template called `base.html` in `books/templates/books/base.html`:

{% block title %}My Books{% endblock %}

{% block header %}My Books{% endblock %}

{% block content %}{% endblock %}


10. Create a child template called `index.html` in `books/templates/books/index.html`:

{% extends "base.html" %}

{% block title %}My Books - Index{% endblock %}

{% block header %}Book List{% endblock %}

{% block content %}

{% load books_tags %}

{% book_list %}

{% endblock %}


11. Update the `urls.py` file in your project directory to include the URL pattern for the books app:

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('books/', include('books.urls')),

]


12. Create a new `urls.py` file in the `books` app directory and define a URL pattern for the index view:

from django.urls import path

from .views import BookListView

urlpatterns = [

path('', BookListView.as_view(), name='book_list'),

]


13. Create a new `views.py` file in the `books` app directory and define the `BookListView` class:

from django.views.generic import ListView

from .models import Book

class BookListView(ListView):

model = Book

template_name = 'books/index.html'


14. Run the development server and visit `http://localhost:8000/books/` to see your book list in action.

Common Mistakes

  1. Forgetting to register custom template tags: Make sure you call the register decorator from Django's template module at the beginning of your custom tag file (e.g., books/templatetags/books_tags.py).
  2. Using incorrect syntax for template tags: Ensure that you use the correct syntax for template tags, including proper indentation and spacing.
  3. Misunderstanding blocks and inheritance: Be aware of how blocks and inheritance work in Django templates to avoid confusion when creating or overriding blocks in child templates.
  4. Not loading custom template tag libraries: If you're using a custom template tag library, make sure to load it at the beginning of your template with the {% load %} tag (e.g., {% load books_tags %}).
  5. Forgetting to close template tags: Remember to close all template tags, including loops and conditionals, with their corresponding {% endfor %}, {% endif %}, or {% endwith %} tags.

Practice Questions

  1. Create a custom template tag called current_year that returns the current year as a string.
  2. Modify the book_list template tag to include the publication date of each book in the list.
  3. Create a new template tag called random_book that randomly selects and displays one book from the database.
  4. Write a custom template filter called truncate that truncates a string at a specified length with an ellipsis (...) at the end.

FAQ

--

  1. Why can't I see my custom template tag in the Django admin site?

Custom template tags are not displayed in the Django admin site and do not require any special handling there. They are used exclusively within your project's templates.

  1. What is the difference between a simple tag and a filter in Django template tags?

A simple tag is a standalone function that generates output, while a filter modifies the output of an existing variable or expression. For example, the upper filter converts a string to uppercase, whereas the for loop is a simple tag for iterating over a sequence.

  1. How do I create a custom template tag that takes arguments?

To create a custom template tag with arguments, define your function as a Python class-based view (CBV) and include the arguments in the view's get_context_data method. Then, call the tag within your templates using the arguments enclosed in curly braces {% %}.

  1. What is the purpose of the with template tag in Django?

The {% with %} and {% endwith %} tags create a temporary context within a block, allowing you to assign variables or modify context data without affecting the parent template's context. This can be useful for debugging or temporarily storing values during loops or conditionals.

Tags (Web Development) | Web Development | XQA Learn