Reputation: 2334
I'm working on a flask project. In Jinja template there is a problem for me in the for loop. I want to print the first index of the first index of a dictionary.
The output of newlist
is:
{1: [{'uid': 407, 'color': red},
{'uid': 407, 'color': black},
{'uid': 407, 'color': white}], 2:
[{'uid': 372, 'color': pink},
{'uid': 372, 'color': blue},
{'uid': 372, 'color': orange}], 3:
[{'uid': 28, 'color': green}]}
I want to get the output like this:
{'uid': 407, 'color': red}
{'uid': 407, 'color': black}
{'uid': 407, 'color': white}
{'uid': 372, 'color': pink}
{'uid': 372, 'color': blue}
{'uid': 372, 'color': orange}
{'uid': 28, 'color': green}
How I can edit this for loop to reach that output? Here I have set both indexes manual ( newlist.1.1 )
, how I can increase index number correctly?
{% for each in newlist %}
{{ newlist.1.1 }}<br>
{% endfor %}
Upvotes: 2
Views: 677
Reputation: 10951
Just treat it the way you would treat a dictionary outside the template, that's the point of Jinja templates:
>>> newlist = {1: [{'uid': 407, 'color': 'red'}, {'uid': 407, 'color': 'black'}, {'uid': 407, 'color': 'white'}], 2: [{'uid': 372, 'color': 'pink'}, {'uid': 372, 'color': 'blue'}, {'uid': 372, 'color': 'orange'}], 3: [{'uid': 28, 'color': 'green'}]}
>>>
>>> for k in newlist :
for d in newlist[k]:
print(d)
{'uid': 407, 'color': 'red'}
{'uid': 407, 'color': 'black'}
{'uid': 407, 'color': 'white'}
{'uid': 372, 'color': 'pink'}
{'uid': 372, 'color': 'blue'}
{'uid': 372, 'color': 'orange'}
{'uid': 28, 'color': 'green'}
So, in your template:
{% for k in newlist %}
{% for d in newlist[k] %}
{{ d }}<\br>
{% endfor %}
<\br>
{% endfor %}
Upvotes: 4