2016-06-21 20 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結構,所以它不包含這樣的鑰匙!