簡體   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