Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django templates: value of dictionary key with a space in it

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'] }} 
like image 917
Matt Hampel Avatar asked Jun 03 '10 22:06

Matt Hampel


People also ask

Can DICT key have spaces?

This answer may give the correct "final" answer (yes, spaces are allowed in dictionary key strings), but the reasoning is incorrect. The reason that spaces are allowed inside dictionary key strings has nothing to do with a style guide.

What does {{ NAME }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


2 Answers

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.

like image 189
Sam Dolan Avatar answered Oct 01 '22 01:10

Sam Dolan


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" }} 
like image 25
Tugrul Ates Avatar answered Oct 01 '22 00:10

Tugrul Ates