Custom Template Tags and Filters in Django

Reverie

Custom Template Tags/Filters are necessary when there is a need to modify the object received from views context, such that it suits the needs of rendering them in the template. Django’s out-of-the-box tags/filters might not always suffice. The custom tag/filter can be registered in Django’s tags or filters Library and used in the templates. Let’s learn something about writing our own tags and filters. Let me start off from the beginning:

  • Create a new Django Project:

django-admin startproject <proj_name>

  • Create an app in the project:

python manage.py startapp temptags

  • Add the App to INSTALLED_APPS in settings.py

  • Create a templatetag folder inside the app folder.

  • Create a __init__.py file to treat the folder as python package.

  • Create a ‘templates’ folder to add the html files

  • urls.py

from django.urls import pathfrom . import views

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

  • views.py

from django.shortcuts import render

def sampleTemptag(request):
    context = {
        "name": "My name is Agnes.000123",
        "id": "89752358-1234",
        "fullname": "Agnes George Sequera"}
    return render(request,'main.html',context)

View original post 427 more words

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s