Rusty
Rusty

Reputation: 1371

Django: templates and iterate over dict

I have a dict:

 >>> some_dict
{1: ['String1', 'String2', 'String3','String4' ],
 2: ['String1_2', 'String2_2', 'String3_2', 'String4_2' ],}

In my template i want to iterate over this dict and display values in html. So i sent this dict from view:

return render_to_response('tournament.html', 
        {.....
        'some_dict' : some_dict,
        'some_dict_range' : range(4),
             .....
        })

In tournament.html i trying to iterate over some_dict. I want to get output that should looks like:

'String1', 'String2', 'String3','String4'

 {% for iter1 in some_dict_range%}         
{{some_dict.0.iter1}}<br>{% endfor %}

And as result, i get nothing. But when i trying to get same result without iterator: some_dict.0.0, some_dict.0.1, etc. i get what i need ('String1', 'String2', 'String3','String4'). And when i trying to view values of "iter1" i get the right digits:

 {% for iter1 in some_dict_range%}         
{{iter1}}<br>  {% endfor %}

0, 1, 2 ... Why this doesn't work this way? And if i wrong in design of this, how it should looks like? I mean - what the right way to iterate over this dict and display values in html-template?

Upvotes: 2

Views: 10370

Answers (1)

Jon Clements
Jon Clements

Reputation: 142156

Shouldn't:

{{some_dict.0.iter1}}<br>{% endfor %}

Be:

{{some_dict.iter1.0}}<br>{% endfor %}
            ^^^^^^^

Else you're trying to access some_dict[0] which isn't present...

To avoid passing in the range (as I assume you're wanting to output the dict in key order), you can use the following:

{% for k, v in some_dict.items|sort %}
    Position {{ k }} has a first value of {{ v.0 }} and has:<br>
    {{ v|join:"<br/>" }}
    {% for item in v %}
        {{ item }}
    {% endfor %}
{% endfor %}

Upvotes: 6

Related Questions