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

后端 未结 2 679
离开以前
离开以前 2020-12-01 16:23

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}
<
2条回答
  •  长情又很酷
    2020-12-01 16:49

    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.

提交回复
热议问题