Reputation: 400
I've created a for loop in Jinja, which works alongside Flask but for some reason It's not looping the correct amount of times.
{% if news %}
{% set count = -1 %}
{% for new in news[::-1] %}
{% set count = count + 1 %}
<div class="news" style="display:flex;align-items:center;">
<img src="{{ postpfp[count] }}" style="width:50px;border-radius:50%;margin-right:10px;">
<div style="display:block;">
<p style="margin-top:5px;margin-bottom:-3px;font-size:18px;"><b>{{ new.update }}</b></p>
<p style="font-size:13px;">By {{ new.postby }} | {{ new.postdate }} {{ new.posttime }}</p>
</div>
</div>
{% endfor %}
{% else %}
<p style="margin-top:10px;margin-bottom:-5px;">No Updates to Display</p>
{% endif %}
As you can see, for each row in the news table there is it loops through that many times.
There are 2 rows in the table, yet it only loops through once.
In case you need it, here's my python code:
news = News.query.all()
if news:
pfps = []
for new in news[::-1]:
urls = db.session.query(Users).filter_by(username=new.postby).first().pfpurl
pfps.append(urls)
return render_template('dashboard.html',
user=current_user.username,
email=current_user.email,
admin=current_user.isAdmin,
plan=current_user.plan,
date=current_user.joindate,
pfp=current_user.pfpurl,
news=news,
users=db.session.query(Users).count(),
postpfp=pfps)
Upvotes: 0
Views: 609
Reputation: 11370
Flask has a built-in loop counter:
{{ loop.index }} #counts 1,2,3...
{{ loop.index0 }} #counts 0,1,2,3...
So you can use:
<img src="{{ postpfp[loop.index0] }}"...>
Upvotes: 1
Reputation: 464
Your count
variable is not worked as you might expect due to jinja scope behaviour. count
is -1 at each iteration.
Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope.
Upvotes: 0