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]
And it’s used like:
{% for o in objects %}
<li>{{ dictionary|hash:o.id }}</li>
{% 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.
Want more? I'm not as good at forgetting to update @pushcx on Twitter.
Conversation (5)
Jump to comment form | comments rss [?]Add this link to your feed reader to watch for new replies to this post. | trackback uri [?]Trackback this link in a blog post to create a comment here linking to your post.