繁体   English   中英

(Flask)如何在 html 中创建一个 If 语句来检测 for 循环中的最后一项

[英](Flask) How to make an If statement in html that detects the last item in a for loop

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

我在 flask 上制作了一个 web 应用程序,这是我的文章模板的代码片段每篇文章一个小时,但不是最后一篇{% if post == posts[-1] %}似乎不起作用。

默认情况下 Flask 使用 jinja2 作为默认模板引擎[1] ,这就是您正在使用的。 Jinja2 提供loop.last变量[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 %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM