Python Jinja for循环次数不正确
我在Jinja中创建了一个for循环,它与Flask一起工作,但由于某些原因,它的循环次数不正确Python Jinja for循环次数不正确,python,python-3.x,flask,jinja2,Python,Python 3.x,Flask,Jinja2,我在Jinja中创建了一个for循环,它与Flask一起工作,但由于某些原因,它的循环次数不正确 {% if news %} {% set count = -1 %} {% for new in news[::-1] %} {% set count = count + 1 %} <div class="news" style="display:flex;alig
{% if news %}
{% set count = -1 %}
{% for new in news[::-1] %}
{% set count = count + 1 %}
<div class="news" style="display:flex;align-items:center;">
<img src="{{ postpfp[count] }}" style="width:50px;border-radius:50%;margin-right:10px;">
<div style="display:block;">
<p style="margin-top:5px;margin-bottom:-3px;font-size:18px;"><b>{{ new.update }}</b></p>
<p style="font-size:13px;">By {{ new.postby }} | {{ new.postdate }} {{ new.posttime }}</p>
</div>
</div>
{% endfor %}
{% else %}
<p style="margin-top:10px;margin-bottom:-5px;">No Updates to Display</p>
{% endif %}
由于jinja作用域行为,您的
count
变量的工作方式可能与预期不同<代码>计数在每次迭代时为-1
请记住,不可能在内部设置变量
封锁,让他们出现在外面。这也适用于循环。
该规则的唯一例外是if语句,它不
引入范围
烧瓶有一个内置循环计数器:
{{ loop.index }} #counts 1,2,3...
{{ loop.index0 }} #counts 0,1,2,3...
因此,您可以使用:
<img src="{{ postpfp[loop.index0] }}"...>
你怎么知道它只循环一次?我将count
的值返回到页面,据我所知是0,变量没有显示在块外。and循环。当它只进行一次迭代时,它如何显示两行呢?这是我不确定的,因为在我提供的python代码中,它迭代了两次。
<img src="{{ postpfp[loop.index0] }}"...>