Django 模板:字典键的值,其中有一个空格 [英] Django templates: value of dictionary key with a space in it

查看:28
本文介绍了Django 模板:字典键的值,其中有一个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Django 模板中,有没有办法从包含空格的键中获取值?例如,如果我有一个像这样的字典:

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'] }} 

推荐答案

使用内置标签没有干净的方法可以做到这一点.尝试做类似的事情:

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 }}

会抛出解析错误.

你可以在字典中做一个 for 循环(但它丑陋/低效):

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" %}

或者尝试重构你的 dict 以拥有更容易使用"的键.

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

这篇关于Django 模板:字典键的值,其中有一个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆