[英]How to make a for loop iterate through each item in a string with an if statement?
[英](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.