In jinja template my code is something like this, I m trying to get values from my MongoDB database
{% for a in output %}
{{ a.product_name }}
{% else %}
<p> No product found </p>
{% endfor %}
Some HTML CODE
{% for b in output %}
{{ b.product_name }}
{% endfor %}
The problem is first loop is working fine, but second loop not at all working. But when I write the second loop before first loop, then second loop work but then not first loop ( it going inside else and printing "No Product Found").
I am not able to understand this problem.
You want to iterate over the mongodb cursor twice. So after first iteration, you need to call the rewind method on the output (cursor) somewhere between the two loops.
output.rewind()
I am not sure if you would be able to do this in the Jinja template itself.
So the better option would be to convert the pymongo cursor object into a list itself, so you can iterate multiple times.
output_as_list = list(output)
Now you should be able to use output_as_list in your code the way you expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With