Django Template Tag for Dictionary Access «
»


Code: , , ,
6 comments

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.


Comments

  1. funny… I did this exact filter over a year-and-a-half ago. What you describe drove me crazy and I had to do it all the time.

  2. Michael: That’s a nice workaround. I’m on 0.96 so I won’t have ‘with’ available until the next release, but I’ll keep that one in mind.

  3. > Annoyingly, you can’t do dictionary|hash:o.id|hash:’foo’ to get at an inner hash — anyone know why?

    It works for me. Ensure that you have inner dictionary and wrap key in double quotes instead of single quotes:
    dictionary|hash:o.id|hash:"foo"

  4. Michael,

    That workaround sure looks sweet, but it doesn’t seem to work. Seems like there is some context pushing in WithNode that may be getting in the way. (Note that I can have the template emit {{ dictionary }} or {{ key }} and both look fine, however {{ dictionary.key }} emits nothing.)

Leave a Reply

Your email address will not be published.