【问题标题】:(Flask) How to make an If statement in html that detects the last item in a for loop(Flask)如何在html中创建一个If语句来检测for循环中的最后一项
【发布时间】:2021-07-05 19:45:17
【问题描述】:
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
        {% for post in posts %}
          <div class="post-preview">
            <a href="{{ url_for('post', post_id=post.id) }}">
              <h2 class="post-title">
                {{ post.title }}
              </h2>
              <h3 class="post-subtitle">
                {{ post.subtitle }}
              </h3>
            </a>
            <p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
          </div>

            {% if post == posts[-1]  %}
              <br />
            {% else %}
              <hr />
            {% endif %}
          {% endfor %}

我正在烧瓶上创建一个 Web 应用程序,这是我的文章模板的代码的 sn-p 我有一个包含文章的 sqlite 数据库,我如何制作一个 if 语句来检测帖子是否是最后一篇循环,因为我每篇文章都做了一个小时,但不是在最后一篇 {% if post == posts[-1] %} 似乎不起作用。

【问题讨论】:

  • 除非我不明白你的问题,你不需要检查你是否已经到达循环中的最后一个来添加 hr 标签,为什么不在循环之后使用 hr 标签?
  • 有多个帖子,我想显示每个帖子的小时数,而不是最后一个
  • 如果 i != 0,您总是可以执行 for i,post in enumerate(posts),然后在循环的开头执行 &lt;hr&gt;

标签: python html flask frontend flask-sqlalchemy


【解决方案1】:

默认情况下,Flask 使用 jinja2 作为默认模板引擎[1],这就是您正在使用的。 Jinja2 提供了loop.lastvariable[2],你可以使用如下:

<div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
        {% for post in posts %}
          <div class="post-preview">
            <a href="{{ url_for('post', post_id=post.id) }}">
              <h2 class="post-title">
                {{ post.title }}
              </h2>
              <h3 class="post-subtitle">
                {{ post.subtitle }}
              </h3>
            </a>
            <p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
          </div>

            {% if loop.last  %}
              <br />
            {% else %}
              <hr />
            {% endif %}
          {% endfor %}

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2023-03-10
    • 2021-04-30
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    相关资源
    最近更新 更多