您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Django templates:字典键的值,其中有一个空格

Django templates:字典键的值,其中有一个空格

没有干净的方法使用内置标签来执行此操作。尝试做类似的事情:

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

将引发解析错误

你可以在字典中进行for循环(但丑陋/效率低下):

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

自定义标签可能更干净:

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, '')

并在模板中使用它,如下所示:

{% dictKeyLookup your_dict_passed_into_context "Restaurant Name" %}

或者,也许尝试重组你的字典,使其具有“更易于使用”的键。

Go 2022/1/1 18:23:00 有343人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶