DEV Community

Cover image for Custom Template Tags in Django
Sumit Roy
Sumit Roy

Posted on • Updated on

Custom Template Tags in Django

Template Tags

Django has this amazing feature of templating static HTML files to serve them as dynamic pages. If I want to add a title to my web page.

....
<title> Homee </title>
....
Enter fullscreen mode Exit fullscreen mode

But what if I want to add different titles for different pages? Like Home for home page and cart page as Cart.

So for this we use template tags already defined in Django. I use

{% block title %}
<title>Home</title>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

for replacing title blocks in each page extended from a base template with a blank title block like this

{% block title %}
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

using another pre-defined template tag

{% extends 'base.html %}
Enter fullscreen mode Exit fullscreen mode

How to create one?

Well now sometimes these predefined template tags are not well enough to solve your problem together. Say you want one tag which can give you the modulo of the number of elements in a passed object and any integer. This can be useful if you want different column offset in bootstrap according to the number of elements.

These are the few steps you must follow:-

  • Create a templatetags folder in one of the app which is in INSTALLED_APPS arrray in settings file of the project
  • Create a blank init.py file inside templatetags folder o make Python treat the directories as containing packages.
  • Create the custom tags file such as custom_tags.py
  • Inside that, we have to write function for our custom template tag
from django import template

register = template.Library()

@register.filter
def remainder(value, arg):
    return value % arg
Enter fullscreen mode Exit fullscreen mode

Here we registering a custom tag with name remainder which takes value and arg from template like this

{{ value|remainder:arg }}
Enter fullscreen mode Exit fullscreen mode

and returns the remainder.

How to use it?

First, we have to load the custom tag. And then we can use them as we want. I am checking the number of coins is even or not.

{% load custom_tags %}
...
...
{% if coin|remainder:2 == 0 %}
<p> You have even number of coins </p>
{% else %}
<p> You have odd number of coins </p>
{% endif %}
...
...
Enter fullscreen mode Exit fullscreen mode

This is a very simple example of using custom template tags. You can read the full documentation of Django here regarding this topic to get some more advanced idea of how to use template tags.

Liked my post?

Top comments (2)

Collapse
 
svemaraju profile image
Srikanth • Edited

Nice to see you here man! Good going. :)

Collapse
 
artu_hnrq profile image
Arthur Henrique

I like the explanation, simple and direct! Thanks