Django Template Tag for Dictionary Access
About a million times when writing Django pages I’ve been iterating through a list of objects and wanted to look up a value in a dictionary keyed by object.id
. But you can’t, the built-in tags don’t allow it.
The standard workaround is to loop over the list and zip the hash data into some kind of bigger list, but this is expensive if the list is big and just plain annoying, especially if you’re on Django 0.96 and can’t unpack tuples with your for
tag.
So I finally hacked up a template tag to give me access to dictionary contents:
` @register.filter def hash(h, key): return h[key] `{lang=”python”}
And it’s used like:
{% for o in objects %}
{{ dictionary|hash:o.id }}
{% endfor %}
It may not be beautiful, but it mostly works. Annoyingly, you can’t do dictionary\|hash:o.id\|hash:'foo'
to get at an inner hash -- anyone know why?
2011-02-19: Good criticism of this tag on a wontfix Django bug.