By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content.
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Django Custom Template Tags And Filters

Django Template Tags are simple Python functions which accepts a 1 or more value, an optional argument, process those values and return a value to be displayed on the page.

First, In your application folder, create a "templatetags" directory at the same level as the models and views.

You want this directory to be recognized as a Python package, so make sure you create an empty "__init__.py" file. Next, create the Python file that will hold your tags and name it something like app_tags.py.

Here is the folder structure should look like:

Django Project

  -> my_app

    ---> models.py

    ---> views.py

    ---> templatetags

      -----> __init__.py

      -----> app_tags.py

Tags:

Tags look like this: {% tag %}. Tags can be used to create text in the output, control flow by performing loops or logic, and to load external information into the template.

Tags require beginning and ending tags (i.e. {% tag %} ... tag contents ... {% endtag %}).

Django provides about twenty built-in template tags. Here are some of the more commonly used tags

 for - Loop over each item in an array.
 if, elif, and else - Evaluates a variable, and if that variable is “true” the contents of the block are displayed

Defining own Custom Template Tags:

In Your app_tags.py

from django import template

register = template.Library()

@register.assignment_tag
def get_result_tag(arg1, arg2, arg3):
    "----"
    return "response"
register = template.Library(): This refers that you need to make sure, your templates are added to the existing library of tags and filters that Django knows about. This statement gives an instance of the library so you can register your filters. In this post you'll see that I use the handy "@register.assignment_tag" decorator to register it with Django.

 

The above template tag can be used in template after enabling your custom tags by using "{% load app_tags %}".
An example on how to use these functions in your template:

In Your template "example.html"

{% load app_tags %}

{% get_result_tag arg1 arg2 arg3 as result %}
The above tag provides the response from template tag "get_result_tag", can be used with the variable "result".


Filters:

With the use of filters, we can change the text, do arithmetic operations, know the file size, get the date etc.

Here are some of the commonly used filters

    length -- To know string, list size({{ value|length }})
  date -- Formats a date according to the given format.( {{ value|date:"D d M Y" }}, {{ value|date:"m/d/Y H:i:s"}} )
    File Size -- To get the file size in Mb, Bytes( {{ value|filesizeformat }} )
    Sorting a Dictionary -- To sort a list of dictionaries with a given key( {{ value|dictsort:"country_id" }} )

Here is the sample code for the custom filter

@register.filter
def get_modules(value, arg):
    chapter = InstituteChapter.objects.filter(id=value)
    if chapter:
        modules = InstituteChapterTree.objects.filter(chapter_id=chapter[0].chapter_id,institute_id=arg,node_type="Module",status__in=['Draft','Complete'])
        return len(modules)
    return 0

Here @register will register this custom filter with django. I'm using this filter to get the modules count for a given chapter.

We can use this filter in templates like this

{% chapter_id|get_modules:institute_id %}

You can play with filters also. Here i'm using multiple filter at once.

@register.filter(name='one_more')
def another_filter(value_1, value_2):
    return value_1.upper(), value_2.lower()
@register.filter()
def custom_filter(another_filter_value, value_3):
    value_1, value_2 = another_filter_value
    print "now you have three arguments, enjoy"
    return value1, value2, value3
{{ 'value1'|another_filter:'value2'|custom_filter:'value3' }}

Here value1, value2 are passes to one_more filter, perform some operations returns those values to custom_filter filter, do the operations.

 

    Posted On
  • 03 February 2015
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
How to create Custom User Model or Extend User Model in Django?

Django provides built in authentication which is good for most of the cases, but you may have needs that are being served with the existing ...

Continue Reading...
Deploying Your Django app on Heroku

Heroku is a platform as a service (PaaS) that enables developers to build and run applications entirely in the cloud.
1. installation
2. Creating and ...

Continue Reading...
Introduction to Django's Class based views - Understanding how a class based view works

Django has MVT architecture. A view in django is just a callable that takes a request and returns a response. But this can be more ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties