How to creating custom template tags and filter in Django

How to creating custom template tags and filter in Django

## **Introduction** Creating custom tags and filter in Django templates is pretty simple. It acts like a custom function that can be used in Django templates. The situation may occur where you need to split a string or you need to access array...

Introduction

Creating custom tags and filter in Django templates is pretty simple. It acts like a custom function that can be used in Django templates. The situation may occur where you need to split a string or you need to access array element using variable as an index, then you have to create custom tags and filter (acts as a function) in Django templates.

You will find that built-in function, such as, split() is there in Python but you won’t be able to use this function directly in Django template. So in this situation you have to create a custom tags or function in Django template

Prerequisites

  • Knowledge of Python and Django

  • Python version – 3.6.5, Django version – 2.2

  • Python and Django setup

Example with Source Code

You generally create a Django project and under your project you have one or more applications.

Project Configuration

Let’s say you have created Django project called myproject and you have also created an app called myapp under myproject. You may check the documentation for creating Django project and apps under project.

I assume you have the required configurations for your myapp in myproject/myproject/settings.py file in INSTALLED_APPS section as below:

INSTALLED_APPS = [
    'myapp.apps.MyappConfig',
    ...
]

The myapp.apps.MyappConfig is formed as a dotted notation from myproject/myapp/apps.py, where you will find the class name as MyappConfig that has name myapp.

Creating Custom Tags and Filter

Let’s say we want to split a string in Django template file but Django does not provide any built-in function, though Python has split() function that cannot be directly used in Django template file.

Therefore we will create custom tags, which will act as a custom function for the Django template.

Now create a directory called templatetags under myproject/myapp directory. Put empty __init__.py under the directory templatetags to ensure that the directory is treated as a Python package.

Your custom tags and filters will live in a module inside the templatetags directory.

Now create a file called myapp_tags.py under templatetags directory and put the below source code into it.

from django import template

register = template.Library()

@register.filter(name='split')
def split(str, key):
    return str.split(key)

To be a valid tag library, the module must contain a module-level variable named register that is a template.Library instance, in which all the tags and filters are registered. So we used the below two lines to register the custom tags:

from django import template

register = template.Library()

Then we have defined our split(str, key) method that basically uses Python’s built-in split(key) function to return the split string into array of strings.

Loading Custom Tags

Now load your custom tags and filter into Django template file using the following line:

{% load myapp_tags %}

Notice myapp_tags is the name of the file.

Usage of the Custom Tags

Let’s say you want to split a string by ‘.’, then following code written into Django template will help you:

{% with string|split:'.' as strs %}
     {% for str in strs %}
         {{ str }}
     {% endfor %}
 {% endwith %}

First we split the string by separator( .) and capture into strs variable. Then we iterate strs array using for loop and capture each value into str variable and print the value of the str.

Note that you must restart the server in order to reflect the changes.

Thanks for reading.

django python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Main Pros and Cons of Django As A Web Framework for Python Developers

India's best Institute for Django Online Training Course & Certification. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

How to Cache Website using Django — Python ?

How to Cache Website using Django — Python ?. In this blog we would discuss caching an entire website(And thus consider it as part 1 of Caching Series).