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
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 %}
{% block main_content%}
Parent: {{ valdict|key:parent }}
Child1: {{ valdict|key:child1 }}
Child2: {{ valdict|key:child2 }}
{% endblock %}
0 comments:
Post a Comment