当前位置: 动力学知识库 > 问答 > 编程问答 >

django template and dictionary of lists

问题描述:

I'm using django's template system, and I'm having the following problem:

I pass a dictionary object, example_dictionary, to the template:

example_dictionary = {key1 : [value11,value12]}

and I want to do the following:

{% for key in example_dictionary %}

// stuff here (1)

{% for value in example_dictionary.key %}

// more stuff here (2)

{% endfor %}

{% endfor %}

However, this does not enter on the second for loop.

Indeed, if I put

{{ key }}

on the (1), it shows the correct key, however,

{{ example_dictionary.key }}

shows nothing.

In this answer, someone proposed using

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

However, this does not work in this case because I want (1) to have information regarding the particular key.

How do I achieve this? Am I missing something?

网友答案:

I supose that you are looking for a nested loop. In external loop you do something with dictionary key and, in nested loop, you iterate over iterable dictionary value, a list in your case.

In this case, this is the control flow that you need:

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

A sample:

example_dictionary = {'a' : [1,2]}
{% for key, value_list  in example_dictionary.items %}
  print key
  {% for value in value_list %}
    print value
  {% endfor %}
{% endfor %}

Results will be:

'a'
1
2

If this is not that you are looking for, please, use a sample to ilustrate your needs.

分享给朋友:
您可能感兴趣的文章:
随机阅读: