How to write Django Custom Template Tags and Filters

In this tutorial, you will learn how to write your own Django Custom Template Tags and Filters. There are lots of built-in template tags and filters in Django. But sometimes these tags are of no use or we need more functionality to do. For such a situation we create our own tags and filters.

Django Template Tags are simple Python Functions that accept arguments and after processing returns the values which can be displayed in templates. These tags are used in templates or in HTML. You can extend the template engine by defining custom tags and filters.

Getting started.

The most common place for defining template tags are inside Django App. Create an app named core and add that app in INSTALLED_APPS. Inside core app, create a folder named templatetags at the level of models.py views.py. And inside templatetags folder create __init__.py file to ensure the directory is treated as a Python package.

Our custom template tags and filters will live in a module inside the templatetags directory. The name of the module file is that the name you’ll use to load the tags later, thus take care to choose the name of the file that won’t clash with custom tags and filters in another app.

For example, we will be creating a file named custom_tags.py where we will be writing our tags and filters.

Our app layout should look like this –

core/
     __init__.py
     models.py
     templatetags/
         __init__.py
         custom_tags.py
     views.py

And for loading the tags you should use like this in your template –

{% load custom_tags %}

Writing Custom Template Filters

Custom filters are just Python functions that take one or two arguments:

Here’s an example filter definition:

def uppercase(value, arg):
    """Removes all values of arg from the given string"""
    return value.replace(arg, '')

And here’s an example of how that filter would be used:

{{ somevariable|uppercase:"0" }}

Registering Custom Filters

For using the filters, we need to register it with Library instance, to make it available to Django Template.

from django import template

register = template.Library()

and for registering you can use decorator like this –

@register.filter(name='uppercase')

Here is the example of Django filter for making string lowercase and initial first character capital-

# templatetags/custom_tags.py
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(name='lower')
@stringfilter # use this if your filter only accepts strings
def lower(value):
    return value.lower()

from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

@register.filter(needs_autoescape=True)
def initial_letter_filter(text, autoescape=True):
    first, other = text[0], text[1:]
    if autoescape:
        esc = conditional_escape
    else:
        esc = lambda x: x
    result = '<strong>%s</strong>%s' % (esc(first), esc(other))
    return mark_safe(result)

And here how you can use and load those filters in the template –

{% load custom_tags %}
<h2>Home Page - Template Tags</h2>

<p>Lower Template Tag (converts HaPpY to happy) - {{ "HaPpY" |lower }}</p>

<p>initial_letter_filter - {{"happy"|initial_letter_filter}}</p>

To read more about custom filters – Official Site

Writing Custom Template Tags

Django Template Tags are than filters, which can do anything (complex task as well) as compare to filters. Django has shortcuts for making template tags. We can develop tags using those shortcuts. We will mostly use Django simple tags and inclusion tags. Template tags can also take n number of arguments and return value.

Here’s an example tags definition:

@register.simple_tag
def current_time(format_string):
    return datetime.now().strftime(format_string)

And here’s an example of how that tags would be used:

current_time - {% current_time "%Y-%m-%d %I:%M %p" %}

Registering Custom Tags

For using the tags, we need to register it with Library instance, to make it available to Django Template.

from django import template

register = template.Library()

and for registering you can use simple_tag or inclusion_tag decorator like this –

@register.simple_tag(name='uppercase')

@register.inclusion_tag('results.html')

Simple Tags ( simple_tag ) – Using this shortcut, you can easily create template tags. These tags can take one or more arguments and n number of positional arguments.

Inclusion Tags ( inclusion_tag ) – This is another tag that displays data by rendering another template.

Here is an example of Django Simple Tags –

from django import template

register = template.Library()

from datetime import datetime
@register.simple_tag
def current_time(format_string):
    return datetime.now().strftime(format_string)

register.simple_tag(lambda x: x - 1, name='minusone')

@register.simple_tag(name='minustwo')
def some_function(value):
    return value - 2

@register.simple_tag
def my_tag(a, b, *args, **kwargs):
    warning = kwargs['warning']
    profile = kwargs['profile']
    return warning

And here how you can use and load those simple tags in the template –

Tags
<p>current_time - {% current_time "%Y-%m-%d %I:%M %p" %}</p>

<p>minusone - {% minusone 2 %}</p>
<p>minustwo - {% minustwo 5 %}</p>

<p>Position arg - {% my_tag 123 "abcd" book.title warning="This is warning"|lower profile=1 %}</p>

{% current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>

Here is an example of Django Inclusion Tags –

from django import template

register = template.Library()

from django.contrib.auth.models import User
@register.inclusion_tag('results.html')
def show_results():
      obj = User.objects.values_list('username', flat=True)
      return {'choices': obj}

We are including results.html, so here is results.html

<ul>
{% for choice in choices %}
    <li> {{ choice }} </li>
{% endfor %}
</ul>

And here how you can use and load those inclusion tags in the template –

Tags
<p>Inclusion Tag - {% show_results %}</p>

GitHub – Run Example Locally

Code is also available on GitHub – https://github.com/studygyaan/How-to-write-Django-Custom-Template-Tags-and-Filters

Clone the Repository

git clone https://github.com/studygyaan/How-to-write-Django-Custom-Template-Tags-and-Filters

Change Directory

cd How-to-write-Django-Custom-Template-Tags-and-Filters

Create Virtual Environment – VirtualENV

virtualenv env

Activate Virtual Environment

source env/bin/activate

Run requirements file to install libraries using Pip3

pip3 install -r requirements.txt

Run the server

python3 manage.py runserver

And open http://localhost:8000/ in your browser.

Share