简体   繁体   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 %}

Im making a web application on flask and this is the snippet of my code to the articles template I have a sqlite database that contains the articles, how can I make an if statement that detects if the post is the last in the loop since im making an hr per article but not on the last one {% if post == posts[-1] %} doesn't seem to work.我在 flask 上制作了一个 web 应用程序,这是我的文章模板的代码片段每篇文章一个小时,但不是最后一篇{% if post == posts[-1] %}似乎不起作用。

By Default Flask uses jinja2 as default Template Engine [1] and that's what you're using.默认情况下 Flask 使用 jinja2 作为默认模板引擎[1] ,这就是您正在使用的。 Jinja2 provides loop.last variable [2] that you can use as follows: 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