Jinja for 循环没有循环正确的次数

Jinja for loop not looping the correct amount of times

我在 Jinja 中创建了一个 for 循环,它与 Flask 一起工作,但出于某种原因它没有循环正确的次数。

          {% 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 %}

如您所见,新闻中的每一行 table 都循环了那么多次。
table中有2行,但只循环一次。

数据库Table:

如果您需要,这是我的 python 代码:

        news = News.query.all()
        if news:
            pfps = []
            for new in news[::-1]:
                urls = db.session.query(Users).filter_by(username=new.postby).first().pfpurl
                pfps.append(urls)
                
            return render_template('dashboard.html', 
                user=current_user.username,
                email=current_user.email,
                admin=current_user.isAdmin,
                plan=current_user.plan,
                date=current_user.joindate,
                pfp=current_user.pfpurl,
                news=news,
                users=db.session.query(Users).count(),
                postpfp=pfps)

由于 jinja 范围行为,您的 count 变量没有像您预期的那样工作。 count 每次迭代都是-1。

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope.

Reference

Flask 有一个 built-in 循环计数器:

{{ loop.index }} #counts  1,2,3...
{{ loop.index0 }} #counts 0,1,2,3...

所以你可以使用:

<img src="{{ postpfp[loop.index0] }}"...>