Wednesday, November 7, 2012

Writing Custom Template Tags in Django

Django templates are the view part of the Django MVC. So, the templates should just handle the display part and any login in templates should be kept to a minimum. However, there are times when we just have to include logic in the templates, and using template tags is the most elegant way to handle this. Creating your own custom template tags is fairly simple.

One template tag needed often is to get the value from a dictionary.

We like passing dictionaries to templates because dictionaries keep everything readable, especially when I have a long list of parameters to pass to the template. Django templates have no in-built mechanism to retrieve a specific key from the dictionary. So we will write our custom template tag to do that.

Create a directory tempatetags/ under your apps directory. In this directory create a file custom_filters.py.

from django import template

register = template.Library()

@register.filter('key')
def key(d, key_name):
    try:
       value = d[key_name]
    except KeyError:
       # handle the error
       raise Http404  
    return value


Now, from views.py, we pass a dictionary to the template. Say
valdict = {'parent':'Mr John Doer', 'child1':'Emily Doer', 'child2':'Mark Doer'}

To access the dictionary keys in the template we do,

template.html.

{% load custom_filters %}

{% block main_content%}
Parent: {{ valdict|key:parent }}
Child1: {{ valdict|key:child1 }}
Child2: {{ valdict|key:child2 }}
{% endblock %}


0 comments:

Post a Comment