Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 831
Jorge Leitao Avatar asked Nov 26 '12 08:11

Jorge Leitao


1 Answers

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:

#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 %}

Results will be:

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

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

like image 111
dani herrera Avatar answered Oct 19 '22 01:10

dani herrera