Create custom Template Tags in Django

  • By PyCat
  • Jun 03, 2016
  • Django Practices

[Photo by ]

Writing custom template tags

Django custom template tags can do anything. Django provides a number of shortcuts that make writing most types of tags easier. The most common place to specify custom template tags is inside you Django app. The app should contain a templatetags  directory (at the same level as, etc). If it does'nt already exists you can create it manual.

Your app layout should look like this:



*Don’t forget the file to ensure the directory is treated as a Python package.


In the example above we 're going to write an inclusion_tag

This type is a common type o template tags that displays some data by rendering another template. In the example above we will write an inclusion_tag that helps us to render one part of the main menu within the base template.


We are going to use the inclusion_tag library:



Then we can write our script within the file. The code looks like this:

from django import template
from portfolio.models import Page

register = template.Library()


Now let's explain the above code line by line

from django import template
register = template.Library()


To be a valid tag library, our script must contain a module-leve variable named register, an instance o the template.Library in witch all tags and filters are register in Django.

from portfolio.models import Page

Now this one is simple to explain. In this example we need to display data from the Page model so we need to import the Page model


Next we need to register the tamplate and at the end of our script comes our function, in this example our function is typical to a function.

def show_pages_menu(pages_menu):
    pages_menu = Page.objects.all()
    return { 'pages_menu' : pages_menu }

At this point we'we just finished with the banckend an all we need is to show the results in our template:

{% show_pages_menu pages_menu %}


This was just an example of using Custom Teamplate Tags in Django, you can visit Django's Documentaion page to find out more variations of using  template tags. 

Sources: Django Project

Find me