views:

1281

answers:

2

I'd like to be able to iterate over a dictionary while inside of a for loop in a Django template.

For the sake of this sample, consider the following:

items_list = [ {'key1':'value1', 'key2':'value2'}, {'key1':'value5', 'key2':'value9'} ]

Method #1:

{% for dict in items_list %}
    {% for key,value in dict %}
        <tr>
            <td>{{ key }}</td>
            <td>{{ value }}</td>
        </tr>
    {% endfor %}
{% endfor %}

Method #2:

{% for dict in items_list %}
    {% for node in dict.items %}
        <tr>
            <td>{{ node.0 }}</td>
            <td>{{ node.1 }}</td>
        </tr>
    {% endfor %}
{% endfor %}

Questions

  • Why does Method #1 not work? That seems intuitive to me.
  • Is the way I'm doing it in Method #2 ok or will that cause problems later on?
+5  A: 

The .items property isn't set in method 1. Try this:

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

dict.items() returns a list of key value pairs. But just dict is a dictionary object. http://docs.python.org/library/stdtypes.html#dict.items

Robert
Agreed. Documented here: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
sixthgear
A: 

Hello,

How can I pass a variable in {{ node.X }}, I want to pass X from template(js).
NMarcu