3

I have a dict passed to my template, some of the element names / keys begin with an @ symbol, ie: { '@id': 123, '@name': 'Alex' }

Is there a good / clean way I can access these elements?

Alex Wright
  • 1,751
  • 1
  • 12
  • 13

1 Answers1

3

A custom template tag is the only way to access dictionary keys with special characters. The answer to this question provides a good example.

For the lazy:

from django import template
register = template.Library()

@register.filter
def dictKeyLookup(the_dict, key):
    # Try to fetch from the dict, and if it's not found return an empty string.
    return the_dict.get(key, '')

Which you would use like so:

{% dictKeyLookup your_dict "@blarg!#$^&*" %}

As homework, you could also convert this into a simple filter, which would give you a syntax like:

{{ your_dict|getkey:"@blarg!@#$%" }}
Community
  • 1
  • 1
Evan Brumley
  • 2,468
  • 20
  • 13
  • Thanks. I was expecting as much to be honest, but I'm so new to django I wasn't sure if it was just some syntax I'd missed. I've gone ahead and implemented as a filter, looks fairly neat still. Oh and shouldn't it be `{{ dict|getkey:"name" }}` for the filter? And not `{% ... %}`. – Alex Wright Dec 27 '11 at 01:05