2017-05-04 75 views
1

從字典檢索值我有以下情況:我正在尋找一個快速的方式在模板

{% if accounts.count > 0 %} 
    {% for account in accounts %} 
     <div>Balance:<b>{{ my_dict.account.id }}</b></div> 
     <div><a href="/edit/{{ account.id }}"><button>Edit</button></a></div> 
    {% endfor %} 
{% else %} 
    <p>...</p> 
{% endif %} 

這樣的安排是好的

my_dict.account 

但我會做這樣的事情。我有兩個點

my_dict.account.id

有沒有辦法做到這一點?這是創建模板一個變量是個好主意,但它不爲我工作

+0

那麼my_dict是什麼? – ozgur

+1

[Django模板如何用變量查找字典值]的可能重複(http://stackoverflow.com/questions/8000022/django-template-how-to-look-up-a-dictionary-value-with -a-variable) – Geotob

+0

我不想創建自己的過濾器。所以這不是一回事 – programmerJavaPL

回答

0

會很高興地看到你的my_dict字典結構:什麼是關鍵(是佔到ID?)

它可以是這樣的:

my_dict[account.id] 

但如果my_dict不知何故沒有鑰匙,你會遇到一個錯誤。所以,你可能想這樣做,而不是:

my_dict.get(account.id, 'default value') 

「默認值」是什麼將在情況下,如果有一個在my_dict沒有這樣的鍵返回。