In this article we are going to create a custom template tag for our django project and use it in one of our django templates. This article assumes that you are already familiar with django and python and have a sample django project setup already. In this example we are going to create a custom template tag that returns a hours as a list. For example [’00’, ’01’, ’02’ … ] and we are going to call it hour_range.

For creating a custom template tag in django first you need to understand the directory structure / hierarchy and where django will look for registered template tags. Let’s say we have a project with 2 apps registered in our settings.py: books and authors and this is how our directory structure looks like.

Django looks for custom template tags in a folder named templatetags in all of your registered applications. In this example we are going to create our custom template tag under the authors application. So first we create a folder named templatetags within our authors application.

Now we want to make sure that modules from the templatetags folder can be imported, so we create an __init__.py file in the new templatetags folder.

Now this is how our directory structure looks like:

Now let’s create a module inside the templatetags directory that will contain our custom template tag method.

In this file we can put our template tag code

Custom Template Tag Usage

Now inside your template that you want to use your custom template tag, First load the “mytags” module and then use the “hour_range” template tag.

There you have the list of hours. But this prints the list as is. What if we want include our custom template tag inside a for loop and print each item one by one. In such a case we will register our template tag with register.assignment_tag decorator.

and then include render it as follows in your django template.