Search Here

How to Create a Custom Template Tags and Filters in Django Framework

In Django Template, Tags and Filters are used to modify or alter the text rendered via Template. Django has many built-in Template Tags and Filters.

You can also create your custom tags or filter by following the methods shown in this post.

Creating a Template Tag

The Template Tags and filters can be defined inside templatetags folder. And by default, Django looks for templatetags folder in the app directory.

Here we’ll be creating a simple_tag that displays the current time. And for that, we have to import from django import template. And use @register.simple_tag decorator to mark the function current_time as a template tag.
In home\templatetags\datetime_tags.py

from django import template
import datetime

register = template.Library()

@register.simple_tag
def current_time(format_string="%d-%B-%Y"):
    return datetime.datetime.now().strftime(format_string)

Loading Template Tag in HTML Template

To use the current_time tag call {% load datetime_tags %} in Template. This will load all the tags from datetime_tags.py file.

{% load datetime_tags %}
Current Time is {% current_time %} // without paramters
Current Time is {% current_time format_string="%Y-%m-%d" %} // with paramters

Creating a Filter

A filter is basically used to modify the data in the template. Some of the built-in filters are add, length, and click to learn more about Django Template Filters.

Use @register.filter decorator to register function as a filter.

In home\templatetags\product_tags.py

from django import template

register = template.Library()

@register.filter
def format_currency(value, decimals=0):
    return round( value, decimals )

Including template filters in Template

Including filters is the same as including a template tags file. But to call the filter use the | pipe symbol.

{% load product_tags %}
Product Price {{55.02026262}} // without paramters
Product Price {{55.02026262|format_currency:4}} // with parameters