Django: templates and iterate over dict
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 %}
Rusty
Updated on June 04, 2022Comments
-
Rusty almost 2 years
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?
-
Rusty almost 12 yearsI was correct - some_dict.0.iter1. When i trying to iterate "some_dict.0.1", "some_dict.0.2" etc. - i get my values
-
marianobianchi almost 12 yearsIf you access with some_dict.0.X, you dictionary must have "0" as a key because if not, you should get a KeyError raised. Is your example correct? @JonClements is right, take a look at this if you don't believe us...
-
Rusty almost 12 yearsYep, this is my mistake - i have a key '0', not '1'. Thx to @JonClements, his solution works perfect
-
Rusty almost 12 yearsAnd i was wrong again - solution is not perfect. What if i want to iterate over "{{ v.0 }}". I mean i want to {{v.x}} where x - is iterator. When i try to {% for x in z%} {{v.x}} {% endfor %} - i got nothing. (z is a range(4), for example)
-
Rusty almost 12 yearsThx, this is want i search for
-
NaturalBornCamper about 6 yearsI don't think the "|sort" filter is working, unless I'm wrong but I tried it and it's not working