Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loop not working in Jinja/Flask

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.

like image 663
Arpit Kanodia Avatar asked Dec 02 '25 22:12

Arpit Kanodia


1 Answers

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.

like image 157
masnun Avatar answered Dec 05 '25 14:12

masnun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!