2011-11-24 66 views
6

我們已經建立了一個自定義的數據庫,其中的許多屬性被命名爲含連字符的系統,即:如何從Django模板中訪問包含連字符的字典鍵?

user-name 
phone-number 

這些屬性不能在模板中訪問如下:

{{ user-name }} 

Django的投這是一個例外。我想避免必須轉換所有的鍵(和子表鍵)才能使用下劃線來解決這個問題。有更容易的方法嗎?

回答

8

如果您不想重構對象,自定義模板標記可能是唯一的途徑。對於使用任意字符串鍵訪問字典,this question的答案提供了一個很好的例子。

對於懶:

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 "phone-number" %} 

如果你想用一個任意字符串名稱訪問對象的屬性,你可以使用以下命令:

from django import template 
register = template.Library() 

@register.simple_tag 
def attributeLookup(the_object, attribute_name): 
    # Try to fetch from the object, and if it's not found return None. 
    return getattr(the_object, attribute_name, None) 

你會喜歡哪一種:

{% attributeLookup your_object_passed_into_context "phone-number" %} 

你甚至可以拿出某種形式的字符串分隔符的(如「__」)的子屬性,但我會離開,對於功課:-)

+1

我已經使用這個解決方案,但改變了它從一個標籤到一個過濾器。它運作良好,謝謝! – jthompson

+0

這絕對有效,但是如何訪問包含字典作爲值的字典中的密鑰? – Kim

3

不幸的是,我想你可能會走運。從docs

變量名必須由任何字母(A-Z),任何數字(0-9),一個 下劃線或點的。

+0

權。我也發現了一個類似的問題:http://stackoverflow.com/questions/2213308/why-cant-i-do-a-hyphen-in-django-template-view – jthompson

1

OrderedDict字典類型支持破折號: https://docs.python.org/2/library/collections.html#ordereddict-objects

這似乎是實施OrderedDict的副作用。注意下面的關鍵值對實際上是作爲集合傳入的。我敢打賭,OrderedDict的實現不會使用集合中傳遞的「key」作爲真正的詞典關鍵,從而避免了這個問題。

由於這是OrderedDict實現的一個副作用,它可能不是你想要依賴的東西。但它的工作。

from collections import OrderedDict 

my_dict = OrderedDict([ 
    ('has-dash', 'has dash value'), 
    ('no dash', 'no dash value') 
]) 

print('has-dash: ' + my_dict['has-dash']) 
print('no dash: ' + my_dict['no dash']) 

結果:

has-dash: has dash value 
no dash: no dash value 
相關問題