Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Django

Django Inclusion Tags

2022-07-20

Django’s template system comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag.

Custom template tags and filters must be inside a Django app. If they relate to an existing app it makes sense to create them there; otherwise, you should create a new app to hold them.

The app should contain a template tags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget to include __init__.py file to ensure the directory is treated as a Python package.

Your custom tags and filters will be there in a module inside the template tags directory. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app.

For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this:

polls/
    |- __init__.py
    |- models.py
    |- templatetags/
        |- __init__.py
        |- poll_extras.py
    |- urls.py
    |- views.py

And in your template you would use the following:  {% load poll_extras %}

The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work.
Note: A {% load %} statement will load tags/filters for the given Python module name, not the name of the app.

♦ Import the Django template module and register, like so:

from django import template
register = template.Library()

To be a valid tag library, the module must contain a module-level variable named register that is a template.Library instance, in which all the tags and filters are registered.

Inclusion tags:

Another common type of template tag is the type that displays some data by rendering another template. Writing inclusion tags is probably best demonstrated by example. Let’s write a tag that outputs a list of choices for a given Poll object.

First, define the function that takes the argument and produces a dictionary of data for the result.

def show_results(poll):
      choices = poll.choice_set.all()
      return {'choices': choices}

Next, create the template called "results.html" which is used to render the tag’s output.

  • {% for choice in choices %}
  • {{ choice }}
  • {% endfor %}

Now, create and register the inclusion tag by calling the inclusion_tag() method on a Library object.

register.inclusion_tag('results.html')(show_results)   # Here register is a django.template.Library instance

Now, We’ll use the tag like this:

{% show_results poll %}

and the output will be something like this:

  • First choice
  • Second choice