儘管我已經使用自定義過濾器通過變量鍵訪問字典的值,但我無法這樣做。以下是代碼片段。無法使用Django模板中的過濾器使用變量鍵訪問上下文字典值
view.py
def DBConnect(request):
c = {}
c['dbs'] = get_all_db() #returns an array of db.
for db in c['dbs']:
c[db] = get_all_tables(db) #returns all the tables in db and storing in context dictionary with db name as key.
return render_to_response('test.html', c)
作爲一個實施例C將包含如下: C = { 'DBS':[u'db1' ,u'db2 '],u'db1':[U」 TB1' ,u'tb2 '],u'db2':[u'tb21' ,u'tb22' ]}
app_filter.py
@filter.filter
def get_item(dictionary, key):
return dictionary.get(key)
的test.html .... 。 ...
{%for db in dbs%}
do something with {{db}} <- this is fine, I am getting all the dbs here.
{{ c | get_item : db }} <- This code is not working, If I directly pass dbname literal than it is working fine.
{% endfor %}
請建議我是否應以不同的方式通過上下文來解決此問題。 在此先感謝。
你通過「星展銀行」到測試模板?根據上面的代碼,您傳遞的是'c',它是'dbs'作爲其中一個關鍵字的字典。 –
謝謝Rohan和AKS的回覆。我對Django框架相當陌生。我將實施這些解決方案並將標記爲答案。我非常確定這兩種解決方案都可以完成這項工作。謝謝AKS的解釋,這真的有助於我理解與Django相關的一些事情。再次感謝你們。 +1爲你們倆。:-) – Amit
@Amit:感謝您的評論,我們很樂意提供幫助。還請閱讀[當某人回答我的問題時該怎麼辦?](http://stackoverflow.com/help/someone-answers)。 – AKS