Arpit Kanodia
Arpit Kanodia

Reputation: 55

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.

Upvotes: 3

Views: 5352

Answers (2)

Ivan Velichko
Ivan Velichko

Reputation: 6709

Looks like the output is an iterator. Try to convert it to a list (or dict) inside a view function.

You can reproduce such behaviour by the next code:

output = (x for x in range(3))
# output = list(output)  # if uncomment this line, the problem will be fixed
for x in output:  # this loop will print values
    print(x)  

for x in output:  # this loop won't
    print(x) 

UPD: Since the output is a mongodb cursor, you can rewind it by calling output.rewind() directly in the template.

{% for a in output %}
    {{ a.product_name }}
{% else %}
    <p> No product found </p>
{% endfor %}

Some HTML CODE

{% set _stub = output.rewind() %}  {# use a stub to suppress undesired output #}

{% for b in output %}
     {{ b.product_name }}
{% endfor %}

Upvotes: 3

masnun
masnun

Reputation: 11906

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.

Upvotes: 4

Related Questions