<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.
By Default Flask uses jinja2 as default Template Engine [1] and that's what you're using. Jinja2 provides loop.last
variable [2] that you can use as follows:
<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 %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.