views:

188

answers:

1

In a Django template, is there a way to get a value from a key that has a space in it? Eg, if I have a dict like:

{"Restaurant Name": Foo}

How can reference that value in my template. Pseudo-syntax might be:

{{ entry['Restaurant Name'] }} 
+4  A: 

There is no clean way to do this with the built-in tags. Trying to do something like:

{{ a.'Restaurant Name'}} or {{ a.Restaurant Name }}

will throw a parse error.

You could do a for loop through the dictionary (but it's ugly):

{% for k, v in your_dict_passed_into_context %}
   {% ifequal k "Restaurant Name" %}
       {{ v }}}
   {% endifequal %}
{% endfor %}

Also, a custom tag would probably be cleaner:

from django import template
register = template.Library()

@register.simple_tag
def dictKeyLookup(the_dict, key):
   try:
       return the_dict[key]
   except KeyError:
       return ''

and use it in the template like so:

{% dictKeyLookup your_dict_passed_into_context "Restaurant Name" %}

Or maybe try to restructure your dict to have "easier to work with" keys.

sdolan
+1 for "maybe try to restructure your dict".
Daniel Roseman