2016-05-17 61 views
1

儘管我已經使用自定義過濾器通過變量鍵訪問字典的值,但我無法這樣做。以下是代碼片段。無法使用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 %} 

請建議我是否應以不同的方式通過上下文來解決此問題。 在此先感謝。

+0

你通過「星展銀行」到測試模板?根據上面的代碼,您傳遞的是'c',它是'dbs'作爲其中一個關鍵字的字典。 –

+0

謝謝Rohan和AKS的回覆。我對Django框架相當陌生。我將實施這些解決方案並將標記爲答案。我非常確定這兩種解決方案都可以完成這項工作。謝謝AKS的解釋,這真的有助於我理解與Django相關的一些事情。再次感謝你們。 +1爲你們倆。:-) – Amit

+0

@Amit:感謝您的評論,我們很樂意提供幫助。還請閱讀[當某人回答我的問題時該怎麼辦?](http://stackoverflow.com/help/someone-answers)。 – AKS

回答

0

由於c是一個方面,它是不是在模板中直接使用。什麼是可用的是按鍵/值,您在上下文中設置,即如果你的環境就像下面:

c = {'dbs':[u'db1', u'db2'], u'db1' : [u'tb1', u'tb2'], u'db2' : [u'tb21', u'tb22']} 

您將能夠訪問dbsdb1db2爲模板裏面的變量。這裏鍵被翻譯成變量,並且上下文中的值是這些變量的值,例如,當您訪問dbs時,您直接訪問c['dbs']

考慮到你在做什麼,我會選擇做像以下:現在

def DBConnect(request): 
    c = {} 
    dbs = get_all_db() #returns an array of db. 
    c['dbtbls'] = {db: get_all_tables(db) for db in dbs} 
    return render_to_response('test.html', c) 

,在模板中可以直接訪問dbtbls.items

{% for db, tbls in dbtbls.items %} 
    do something with {{ db }} here. 
    {{ tbls }} # this is the list of all the tables in the db 
{% endfor %} 
0

在django模板中,上下文變量直接從dbs中看到。你不需要像訪問一樣使用字典。

可以稍微改變的背景下,以適應您的代碼

def DBConnect(request): 
    c = {} 
    c['dbs'] = get_all_db() #returns an array of db. 
    c['dbtables'] = {} 
    for db in c['dbs']: 
     c['dbtables'][db] = get_all_tables(db) 

    return render_to_response('test.html', c) 

然後在模板你可以使用

{%for db in dbs%} 
    do something with {{db}} here. 
    {{ dbtables | get_item : db }} 
{% endfor %} 
相關問題