How to Create Custom Template Tags and Filters in Django?

Published On: 24/12/2022 | Category: Django


Hi Dev,

Are you looking for example of how to create custom template tags and filters in django. We will look at example of how to create custom template tags in django. you can see how to create custom template filters in django. if you want to see example of django create custom template tag example then you are a right place.

In Django Template Tags, which are straightforward Python functions that accept arguments and, after processing, return the values that can be displayed in templates, to construct custom tags and filters that are accessible to templates. HTML or templates both utilise these tags. The template engine can be expanded by creating unique tags and filters.

The Django App is the most popular location for defining template tags. Create an app with the name core, then include it in INSTALLED_APPS. Make a templatetags folder in the core app's models.py and views.py files. To ensure that the directory is considered as a Python package, create the __init__.py file within the templatetags folder.

Here i will give you we will help you to give example of how to create custom template tags and filters in django. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
cd example
django-admin startapp core

Step 3: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app, in setting.py file so our setting file look like this..

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

Now looks like our app directory structure..

├── core
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── models.py
│ ├── templates
│ │ ├── index.html
│ │ └── users.html
│ ├── templatetags
│ │ ├── custom_tags.py
│ │ ├── __init__.py
│ ├── tests.py
│ └── views.py

Step 4: Creating the Views

In this step, we need to configure views. open the core/views.py file and add:

core/views.py
from django.shortcuts import render

# Create your views here.

def index(request):
    context = {
        "author": "bhavesh sonagra",
    }
    return render(request, "index.html", context)  

Step 5: Creating Template Filters

The only thing that filters are is a Python function with one or two arguments. For instance, the filter filter f would be provided to the variable var and argument as arg in the filter {{var|filter_f:arg}}.

simple_tag:

Simple tag accepts a number of arguments and processes them before returning a result. The date and time can be displayed in the template using the straightforward example below.

inclusion_tag:

Common template tags like inclusion tag assist in displaying data by producing another template. This element comes in handy when you need to render data that is shared across multiple pages.

core/templatetags/custom_tag.py
from django import template

register = template.Library()

# Writing Custom Template Filters

def modify_name(value, arg):
    # if arg is first_name: return the first string before space
    if arg == "first_name":
        return value.split(" ")[0]
    # if arg is last_name: return the last string before space
    if arg == "last_name":
        return value.split(" ")[-1]
    # if arg is title_case: return the title case of the string
    if arg == "title_case":
        return value.title()
    return value
    
register.filter('modify_name', modify_name)


# Writing Custom Template Tags

import datetime

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


# Inclusion Tag:

from django.contrib.auth import get_user_model
from django.template.loader import get_template

User = get_user_model()

def show_users_table():
    users = User.objects.all()
    return {'users': users}

users_template = get_template('users.html')
register.inclusion_tag(users_template)(show_users_table)

Step 6: Creating the Templates

Next, then with your text editor create new templates files: core/templates/index.html file and the add:

core/templates/index.html
{% load custom_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</head>
<body>
    <div class="container mt-5 pt-2">
        <div class="row d-flex justify-content-center">
            <div class="col-md-10">
                <div class="card">
                    <div class="card-header">
                        <h4>How to Create Custom Template Tags and Filters in Django? - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <p>{{ author | modify_name:"first_name"}}</p>
                        <p>{{ author | modify_name:"last_name"}}</p>
                        <p>{{ author | modify_name:"title_case"}}</p>
                        <p>{{ author | modify_name:"first_name" | modify_name:"title_case"}}</p>

                        <br>

                        <p>{% current_time "%d/%m/%Y %H:%M:%S %p" %}</p>

                        <br>

                        <p>{% show_users_table %}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
core/templates/users.html
{% load custom_tags %}

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Username</th>
            <th>First name</th>
            <th>Last name</th>
            <th>email</th>
        </tr>
    </thead>
    <tbody>
        {% for user in users %}
        <tr>
            <td>{{user.username}}</td>
            <td>{{user.first_name}}</td>
            <td>{{user.last_name}}</td>
            <td>{{user.email}}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>

Step 7: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index),
]

Next, we require to add a URL path for our example project which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

I hope it will help you....

Happy Coding!