2

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

1 Answer 1

4

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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.