Custom Template Blocks in Django

Annika Backstrom
in misc, on 18 September 2007. It is tagged and #Django.

Django includes support for "inclusion tags," shortcuts for reusing a template to generate similarly-structured blocks of text. For example, you could have a template that formats a person's address information like so:

Joe User
1 Main St.
Anytown, NH 03266

Perhaps you want to include this same format on many pages in your site. You could create an {% address_info %} tag to substitute your address template anywhere you wish.

First, create the new template that contains the structure you'd like to repeat. I'll call it address_info.html:

{{ }}<br>
{{ person.addr1 }}<br>
{{ }}, {{ person.state }} {{ }}

Then create a directory in your application to hold the new template tag:

mkdir myapp/templatetags
cd myapp/templatetags

The directory must be named templatetags and must be part of an active ("INSTALLED_APPS") application. must be present to signify the directory as a Python module. can be called whatever you would like. Its contents should look something like this:

from django import template

register = template.Library()

def address_info(person):
    return {'person': person}

The new template tag becomes the function name you used above, in this case {% address_info %}. It takes one argument: a Person model. The final call becomes {% address_info myperson %}.

The last step is to add the tag to your template as necessary. Make sure you load the new template tags file:

{% load myapp_extras %}

{% address_info %}

{% address_info %}