22

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 I reference that value in my template? Pseudo-syntax might be:

{{ entry['Restaurant Name'] }} 
Matt Hampel
  • 5,088
  • 12
  • 52
  • 78

2 Answers2

30

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/inefficient):

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

A custom tag would probably be cleaner:

from django import template
register = template.Library()

@register.simple_tag
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, '')

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.

Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
  • If you're dictionary is nested this works well: `result = the_dict; for key in keys: if hasattr(result, 'get'): result = result.get(key, ''); else: break; return result` – AJP Jul 22 '13 at 10:42
  • Would you know how to combine this with the {% if %} tag in Django? I'm trying to do something like this {% if dictKeyLookup dict_name "key" %} do something {% else %} do something else – him229 Jul 22 '16 at 21:51
16

You can use a custom filter as well.

from django import template
register = template.Library()
    
@register.filter
def get(mapping, key):
    return mapping.get(key, '')

and within the template

{{ entry|get:"Restaurant Name" }} 
Joshua Swain
  • 571
  • 2
  • 4
  • 22
Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
  • Its works for me. Created an folder inside app called templatetag with two files __init__.py and get.py(which holds the above code). Also added {% load get %} in top of html template – Bastin Robin Feb 10 '16 at 07:10
  • 1
    Correction, the directory should be called 'templatetags'; note the 's' at the end. Docs: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/ – user5359531 Jan 03 '19 at 19:30