Django template and list dictionary

I am using the django template system and I am having the following problem:

I pass the 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 is not included in the second cycle of the cycle.

Indeed, if I put

 {{ key }} 

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

 {{ example_dictionary.key }} 

nothing is displayed.

In this answer , someone suggested using

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

However, this does not work in this case, because I want (1) to have information about a specific key.

How do I achieve this? Did I miss something?

+6
source share
1 answer

I suppose you are looking for a nested loop. In the outer loop, you do something with the dictionary key, and in the nested loop, you iterate over the iterable value of the dictionary, the list in your case.

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

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

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 what you are looking for, please use a sample to reflect your needs.

+9
source

All Articles