Custom Template Blocks in 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:
{{ person.name }}<br>
{{ person.addr1 }}<br>
{{ person.city }}, {{ person.state }} {{ person.zip }}
Then create a directory in your application to hold the new template tag:
mkdir myapp/templatetags
cd myapp/templatetags
touch __init__.py myapp_extras.py
The directory must be named templatetags
and must be part of an active
("INSTALLED_APPS
") application. __init__.py
must be present to
signify the directory as a Python module. myapp_extras.py
can be
called whatever you would like. Its contents should look something like
this:
from django import template
register = template.Library()
@register.inclusion_tag('address_info.html')
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 family.dad %}
{% address_info family.mom %}