2016-05-17 10 views
1

私はカスタムフィルタを使用して変数のキーで辞書の値にアクセスしましたが、できません。以下はコードスニペットです。Djangoテンプレートのフィルタを使用して可変キーを使用してコンテキスト辞書の値にアクセスできない

以下を含有する実施例Cとして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 = { '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

あなたがに「DBS」を渡していますテストテンプレート?上のコードでは、キーの1つとして 'dbs'を持つ辞書である 'c'を渡しています。 –

+0

あなたの返信にロハンとAKSありがとうございます。私はDjangoフレームワークにはかなり新しいです。私はこれらのソリューションを実装する予定で、答えとしてマークします。私は両方のソリューションが仕事をすることを確信しています。説明のためにAKSをお願いします。これはDjangoに関連するもののほとんどを理解するのに本当に役立ちます。もうお二人に感謝します。 +1あなたの両方のために.. :-) – Amit

+0

@Amit:コメントいただきありがとうございます、私たちは助けてうれしいです。 [誰かが私の質問に答えたときにはどうすればいいですか?](http://stackoverflow.com/help/someone-answers)も読んでください。 – AKS

答えて

0

を使用することができます

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) 

としてあなたのコードに合わせてコンテキストを変更することができます

は文脈で、それはテンプレートで直接使用できません。鍵である利用できるどのようなものです/あなたがコンテキストに設定された値、すなわち、あなたの状況が似ている場合は、以下:

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のように直接アクセスします。あなたは辞書のようなアクセスを使用する必要はありません。あなたはわずか次にテンプレートであなたがcので

{%for db in dbs%} 
    do something with {{db}} here. 
    {{ dbtables | get_item : db }} 
{% endfor %} 
関連する問題