For 循环在 Jinja/Flask 中不工作
For Loop not working in Jinja/Flask
在 jinja 模板中,我的代码是这样的,我试图从我的 MongoDB 数据库中获取值
{% 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 %}
问题是第一个循环工作正常,但第二个循环根本不工作。但是当我在第一个循环之前写第二个循环时,第二个循环工作但不是第一个循环(它进入 else 并打印 "No Product Found")。
我无法理解这个问题。
看起来 output
是一个 iterator。尝试在视图函数中将其转换为 list
(或 dict
)。
您可以通过下一个代码重现此类行为:
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: 由于 output
是一个 mongodb 游标,您可以通过调用 output.rewind()
directly模板。
{% 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 %}
您想遍历 mongodb 游标两次。因此,在第一次迭代之后,您需要在两个循环之间的某处调用 output
(光标)上的 rewind
方法。
output.rewind()
我不确定您是否能够在 Jinja 模板本身中执行此操作。
所以更好的选择是将 pymongo 游标对象本身转换为列表,这样您就可以迭代多次。
output_as_list = list(output)
现在您应该可以按照预期的方式在代码中使用 output_as_list
。
在 jinja 模板中,我的代码是这样的,我试图从我的 MongoDB 数据库中获取值
{% 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 %}
问题是第一个循环工作正常,但第二个循环根本不工作。但是当我在第一个循环之前写第二个循环时,第二个循环工作但不是第一个循环(它进入 else 并打印 "No Product Found")。
我无法理解这个问题。
看起来 output
是一个 iterator。尝试在视图函数中将其转换为 list
(或 dict
)。
您可以通过下一个代码重现此类行为:
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: 由于 output
是一个 mongodb 游标,您可以通过调用 output.rewind()
directly模板。
{% 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 %}
您想遍历 mongodb 游标两次。因此,在第一次迭代之后,您需要在两个循环之间的某处调用 output
(光标)上的 rewind
方法。
output.rewind()
我不确定您是否能够在 Jinja 模板本身中执行此操作。
所以更好的选择是将 pymongo 游标对象本身转换为列表,这样您就可以迭代多次。
output_as_list = list(output)
现在您应该可以按照预期的方式在代码中使用 output_as_list
。