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

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

问题描述

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

  {餐厅名称:Foo} 

如何在我的模板中引用该值?伪语法可能是:

  {{entry ['Restaurant Name']}} 


解决方案

使用内置的标签没有干净的方法。尝试做以下事情:

  {{a.'Restaurant Name}}}或{{a.Restaurant Name}} 

会抛出一个解析错误。



你可以通过字典做一个循环(但是它的丑陋/低效):

  {%for k,v in your_dict_passed_into_context%} 
{%ifequal k餐厅名称%}
{{v}}
{%endifequal%}
{%endfor%}

自定义标签可能会更干净:

 从django导入模板
register = template.Library()

@ register.simple_tag
def dictKeyLookup(the_dict,key):
#尝试从dict,如果没有找到,返回一个空字符串。
返回the_dict.get(key,'')

并在模板中使用它所以:

  {%dictKeyLookup your_dict_passed_into_context餐厅名称%} 

或者也可以尝试重组您的dict以使更容易使用键。


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

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.

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

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