Mat*_*pel 18 django django-templates
在Django模板中,有没有办法从一个有空格的键中获取值?例如,如果我有一个像这样的字典:
{"Restaurant Name": Foo}
Run Code Online (Sandbox Code Playgroud)
如何在模板中引用该值?伪语法可能是:
{{ entry['Restaurant Name'] }}
Run Code Online (Sandbox Code Playgroud)
Sam*_*lan 23
使用内置标签没有干净的方法.尝试做类似的事情:
{{ a.'Restaurant Name'}} or {{ a.Restaurant Name }}
Run Code Online (Sandbox Code Playgroud)
将抛出一个解析错误.
你可以在字典中做一个for循环(但它很丑/效率低):
{% for k, v in your_dict_passed_into_context %}
{% ifequal k "Restaurant Name" %}
{{ v }}
{% endifequal %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
自定义标签可能更干净:
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, '')
Run Code Online (Sandbox Code Playgroud)
并在模板中使用它,如下所示:
{% dictKeyLookup your_dict_passed_into_context "Restaurant Name" %}
Run Code Online (Sandbox Code Playgroud)
或者也许尝试重组您的词典以使"更容易使用"键.
Tug*_*tes 10
您也可以使用自定义过滤器.
from django import template
register = template.Library()
@register.filter
def get(mapping, key):
return mapping.get(key, '')
Run Code Online (Sandbox Code Playgroud)
并在模板中
{{ entry|get:"Restaurant Name" }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12737 次 |
| 最近记录: |