Saturday 2 May 2009

Custom Template Tags - Part 3: A Last Minute Inclusion

After finishing last week's tutorial on block style template tags I realised that there was one template tag creation tip that I had yet to mention and that's the inclusion tag. This is quite closely related to the simple template tags described previously in that it only requires you to write one function. This time however you must provide also provide a template name which will be rendered at the end of it all. Take a look at the following example (a reworking of the simple tag example)


#File: list_formatters.py
from django import template

register = template.Library()

@register.inclusion_tag('format_list_tag.html')
def format_list(input_list):
return { 'unformatted_list':input_list, }

This file is fairly straightforward, we decorate the format_list function to say that it's an inclusion style tag and that it should use the template format_list_tag.html we then return a dictionary which will be used as the context for the template when it is processed. All that's left to include is the following template file:


{# File: format_list_tag.html #}
<ul>
{% for item in unformatted_list %}
<li>{{ item }}</li>
{% endfor %}
<ul>

This file simply provides a snippet of html describing how to display the list. Pop list_formatters.py into your templatetags directory and format_list_tag.html into your templates directory and pointing a url towards the following example (repeated from the previous tutorial) you can see the tag in action.


from django.template import Template,Context
from django.http import HttpResponse
def tag_test(request):
test_list=['Item 1','Item 2','Third time lucky']
t = Template("""{% load list_formatters %}
<html>
<head><title>Tag Test</title></head>
<body>
{% format_list test_list %}
</body>
</html>""")
return HttpResponse(t.render(Context({'test_list':test_list})))

There is one other useful feature of the inclusion tag and that is the ability to access the context. This can be done as follows (changes from the original file have been highlighted):


#File: list_formatters.py
from django import template

register = template.Library()

@register.inclusion_tag('format_list_tag.html', takes_context=True)
def format_list(context):
return { 'unformatted_list':context.get(test_list,[]), }

Whilst this example isn't really the best way to do things it should illustrate the power of what can be done by the inclusion tag and should enable you to use it in your own django sites.


Next time things will be back on track with the promised tutorial on custom filters

1 comment:

  1. Thanks, I was reading django tutorials but overlooked the {% load ... %} statement. This helped me to get it working.

    ReplyDelete