| « Django 1.0 Website Development | django blog project » |
Monday, August 17th, 2009
Django Templates and Dictionaries
Ever needed to access a python dictionary from a django template? It's pretty straightforward:
{{dictionary.key}} will get you that.
but ever needed to do it inside a loop, with a variable key? django will not allow you to do this default (after finding a solution that worked, i can't BELIEVE that it isn't a part of django already. maybe it is in the new version?)
anyway, i wrote a custom template tag which allows me to access the keys of a dictionary using a variable:
from django import template
register = template.Library()
def dict_get(value, arg):
#custom template tag used like so:
#{{dictionary|dict_get:var}}
#where dictionary is duh a dictionary and var is a variable representing
#one of it's keys
return value[arg]
register.filter('dict_get',dict_get)
now, {{dictionary|dict_get:var}}, where var is one of the dictionary keys, will give me exactly what i want.
update:
there is a big difference that i didn't make obvious in my post.
in view:
dict = {'1':True,'3':False,'5':True}
arr = [1,2,3,4,5]
in template:
{{dict.5}} #evaluates to True
{% for key in arr %}
{{dict.key}} #does not work
{{dict|dict_get:key}} #WORKS!
{% endfor %}
12:35pm by Brandon //comment 2515 views