12

djangoのテンプレートシステムを使用していますが、次の問題が発生しています。

辞書オブジェクトexample_dictionaryをテンプレートに渡します。

example_dictionary = {key1 : [value11,value12]}

そして私は次のことをしたい:

{% for key in example_dictionary %}
// stuff here (1)
{% for value in example_dictionary.key %}
// more stuff here (2)
{% endfor %}
{% endfor %}

ただし、これは2番目のforループには入りません。

確かに、私が置くなら

{{ key }}

(1)では、正しいキーが表示されますが、

{{ example_dictionary.key }}

何も表示されません。

この回答では、誰かが使用することを提案しました

{% for key, value in example_dictionary.items %}

ただし、この場合、(1)特定のキーに関する情報が必要なため、これは機能しません。

どうすればこれを達成できますか?私は何かが足りないのですか?

4

1 に答える 1

15

ネストされたループを探していると思います。外部ループでは、辞書キーで何かを行い、ネストされたループでは、反復可能な辞書値、場合によってはリストを反復処理します。

この場合、必要な制御フローは次のとおりです。

{% for key, value_list  in example_dictionary.items %}
  # stuff here (1)
  {% for value in value_list %}
    # more stuff here (2)
  {% endfor %}
{% endfor %}

サンプル:

#view to template ctx:
example_dictionary = {'a' : [1,2]}

#template:
{% for key, value_list  in example_dictionary.items %}
  The key is {{key}}
  {% for value in value_list %}
    The key is {{key}} and the value is {{value}}
  {% endfor %}
{% endfor %}

結果は次のようになります。

The key is a
The key is a and the value is 1
The key is a and the value is 2

これがあなたが探しているものでない場合は、サンプルを使用してニーズを説明してください.

于 2012-11-26T08:23:14.613 に答える