Template tags are code snippets used to add functionality in templates. Django offers a variety of template tags such as {% if %}, {% for %}, {% block %}. Besides, Django allows us to create our own set of custom tags and make them available in the Django templates. We can extend the template engine by defining custom tags. Then it will be available to our templates. In this tutorial, we will discuss Django Custom Template Tags.

Why We Use Template Tags in Django

Suppose, we have an eCommerce website to build. It will contain multiple category products and we will have to show all the categories in our ‘navbar’. To do this we will have to pass the queryset ‘Categories.objects.all()’ from each of our views to show in each template. But, Using template tags we can skip this redundancy. We will make a custom template tag that will show all the categories and load it into our ‘base.html’ file.

Custom Template Tags in Django

Django provides the following helper functions that allow us to create our own template tags in an easy manner:

  • simple_tag: Processes the data and returns a string
  • inclusion_tag: Processes the data and returns a rendered template.

Simple Tag

It returns simple string.

Let’s start creating our first template tag. Firstly, we will create a directory named ‘templatetags’ & add __inti__.py file to ensure the directory is treated as a Python package. Then we will create another file named new_template_tags.py

directory structure

new_template_tags.py

from first_app.models import Person
from django import template

register = template.Library()

@register.simple_tag
def all_persons():
    return Person.objects.count()

@register.simple_tag
def male_persons():
    return Person.objects.filter(gender='M').count()

I created an instance ‘register’ of ‘template.Library()’ and used it as “@register.simple_tag” decorator. It will help us to register our template into the Django template library. This can be named anything but naming it ‘register’ is strongly recommended.

Now, this template tag can be used inside any template after loading it in the template using “{% load new_template_tags %}”.

Inside ‘persons.html’

{% load new_template_tags %}

<h2>All Persons {% all_persons %}</h2>
<h3>Male Persons {% male_persons %}</h3>

Output:

This is the power of template tags. We can process any data and use them in any template we want.

Inclusion Tag

Inclusion is the kind of template tag which displays some data by rendering a specific template. Now, we will change our ‘all_persons’ tag into an inclusion tag.

new_template_tags.py

@register.inclusion_tag('all_persons.html',takes_context = True )
def all_persons(context):
    # Fetch Data From Person Model
    persons = Person.objects.all()
    context = {
        'persons': persons,
    }
    return context

all_persons.html

{% for person in persons %}

{% if person.first_name == 'Zaira' %}
    <a href="{% url 'person-detail-view' person.id %}">   <h3>{{person.first_name}} {{person.last_name}}</h3></a>
    <h4>{{person.email}}</h4>
{% else %}
    <a href="{% url 'person-detail-view' person.id %}"> <h3>{{person.first_name}} {{person.last_name}}</h3></a>
    <h4>{{person.email}}</h4>
{% endif %}

{% endfor %}

We have retrieved the data rendered by our template tag inside all_persons.html template. Now, this ‘all_persons.html’ can be attached inside any other template.

persons.html

{% extends 'base.html' %}
{% block content %}
<h2>All Persons</h2>

{% all_persons %}

{% endblock %}

Output

We can also pass arguments in our template tags.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)