【问题标题】:Jinja for loop not looping the correct amount of timesJinja for 循环没有循环正确的次数
【发布时间】:2020-09-13 22:08:00
【问题描述】:

我在 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 %}

如您所见,对于新闻表中的每一行,它都会循环多次。
表中有 2 行,但它只循环一次。

数据库表:

如果您需要,这是我的 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)

【问题讨论】:

  • 你怎么知道它只循环一次?
  • 我将count的值返回给页面,是0

标签: python python-3.x flask jinja2


【解决方案1】:

Flask 有一个内置的循环计数器:

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

所以你可以使用:

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

【讨论】:

    【解决方案2】:

    由于 jinja 范围行为,您的 count 变量未按预期工作。 count 在每次迭代时为 -1。

    请记住,不能在 阻止并让他们出现在外面。这也适用于循环。 该规则的唯一例外是 if 语句不 引入范围。

    Reference

    【讨论】:

    • 据我所知,该变量没有出现在块之外。
    • 和循环。那么当它只进行 1 次迭代时它如何显示 2 行?
    • 这是我不确定的,因为在我提供的 python 代码中它会迭代两次。
    猜你喜欢
    • 2018-05-21
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多