Codementor Events

Creating Custom Template Tags In Django Application

Published Feb 13, 2017Last updated Aug 18, 2017
Creating Custom Template Tags In Django Application

Django offers a variety of built-in template tags such as {% if %} or {% block %}.
You have used several in your templates.

However, Django also allows you to create your own template tags to perform custom actions. Custom template tags come in very handy when you need to add functionality to your templates that is not covered by the core set of Django template tags.The power of custom template tags is that you can process any data and add it to any template regardless of the view executed. You can perform QuerySets or process any data to display results in your templates.

Django provides the following helper functions that allow you to create your own
template tags in an easy manner:

  • simple_tag: Processes the data and returns a string
  • inclusion_tag: Processes the data and returns a rendered template
  • assignment_tag: Processes the data and sets a variable in the context

Template tags must live inside Django applications.

Let the Code Begin

Inside your django application directory, create a new directory, name it templatetags and add an empty __init__.py file to it. Create another file in the same folder and name it custom_tags.py. The file structure of the django application should look like the following:

  djangoapp/
      __init__.py
      models.py
      ...
      templatetags/
          __init__.py
          custom_tags.py

The name of the file is important. You are going to use the name of this module to
load your tags in templates.

  1. Simple Tag:
    We will start by creating a simple tag to retrieve the total count of objects in our model named as YourModel.
    Edit the custom_tags.py file you just created and add the following code:
  from django import template
  register = template.Library()

  from ..models import YourModel

  @register.simple_tag
  def any_function():
  	return YourModel.objects.count()

As mentioned above, It processes the data and returns a string. Each template tags module needs to contain a variable called register to be a valid tag library. This variable is an instance of template.Library and it's used to register your own template tags and filters. Django will use the function's name as the tag name.
If you want to register it with a different name, you can do it by specifying a name attribute like @register.simple_tag(name='my_tag').

After adding a new template tags module, you will need to restart
the Django development server in order to use the new template tags and filters.

Before using custom template tags, you have to make them available for the template
using the {% load %} tag. As mentioned before, you need to use the name of the
Python module containing your template tags and filters.

  1. Inclusion Tag:
    This time we are going to use an inclusion tag. Using an inclusion tag, you
    can render a template with context variables returned by your template tag. Edit the custom_tags.py file and add the following code:
  @register.inclusion_tag('path_to_your_html_file.html')
  def any_function():
      variable = YourModel.objects.order_by('-publish')[:5]
      return {'variable': variable}

Notice that the function returns a dictionary of variables instead of a simple value. Inclusion tags have to return a dictionary of values that is used as the context to render the specified template. Inclusion tags return a dictionary.

  1. Assignment Tag:
    Finally, we are going to create an Assignment tag. Assignment tags are like simple tags but they store the result in a given variable.
    Edit the custom_tags.py file and add the following import and template tag in it:
  @register.assignment_tag
  def any_function(count=5):
      return *some database query*

The notation for assignment template tags is {% template_tag as variable %}. We can use assignment tag in our html file like below:

  {% any_function as queries %}
  <ul>
    {% for query in queries %}
      <li>
      ...
      </li>
    {% endfor %}
  </ul>

It's simple to use templates tags in your django application.

Resources

  • You can find a complete reference of custom tempalte tags and filters Here
  • You can find a complete reference of built-in template tags and filters Here.
Discover and read more posts from Hitesh Garg
get started
post commentsBe the first to share your opinion
SunJoo Moon
5 years ago

Many thanks. Now all makes quite clear to me.

LZORZA
7 years ago

Clear and objective, thanks

ADEWALE ADISA
7 years ago

Thanks,

Show more replies