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

from django import template

register = template.Library()

def key(d, key_name):
       value = d[key_name]
    except KeyError:
       # handle the error
       raise Http404  
    return value

Now, from, 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,


{% load custom_filters %}

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

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog.
    Really very informative post you shared here. Kindly keep blogging.
    If anyone wants to become a Front end developer learn from Javascript Online Training from India .
    or learn thru JavaScript Online Training from India.
    Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai