2016-06-21 48 views
0

在django文档中提到。符号会做一个查找按照下面的顺序如何在键有特殊字符时做Django模板字典查找?

#Dictionary lookup. Example: 
foo["bar"] 
#Attribute lookup. Example: 
foo.bar 
#List-index lookup. Example: 
foo[bar] 

在我的项目我有一本字典:

foo = {'ba-r':'...} 

但使用。符号会导致错误,这似乎是因为整个'foo.ba-r'是一个变量,如文档here中所述。

foo.ba-r 

有什么方法可以正确访问我的字典中的'ba-r'键吗?

+0

你有没有理由不能使用foo [“ba-r”]? –

+2

可能的重复[如何从Django模板中访问包含连字符的字典键?](http://stackoverflow.com/questions/8252387/how-do-i-access-dictionary-keys-that-c​​ontain-连字符在django-templa中)和[在Django模板中使用空格键的字典](http://stackoverflow.com/questions/1906129/dict-keys-with-spaces-in-django-templates) – solarissmoke

回答

2

正如您已经发现的那样,您无法在不提高ParseError的情况下访问模板中的此类密钥。您可以使用a custom filter例如:

from django import template 

register = template.Library() 

@register.filter 
def get_key_value(some_dict, key): 
    return some_dict.get(key, '') 

而且使用它像

{{ entry | get_key_value:"ba-r" }} 

或更改dictionnary结构,所以它不包含这样的钥匙!