如果Jinja-for循环什么都不返回,我如何用Flask显示HTML消息



我正在使用Flask,并且正在Jinja中循环遍历表Buyers对象。如果表的特定字段Buyers.supplier中没有数据,我希望在HTML页面中显示一条消息。

假设该表有5个条目,并且不存在字段,那么在我当前的代码中,我看到了5次消息。

如果所有字段都为空,有没有办法只显示HTML消息?非常感谢。

main.html

<div class="card-deck">
{# Go through each blog post #}
{% for sched in buyer_sched|sort(attribute='time') %}
{# Only show if a supplier has been matched#}
{% if sched.supplier.company %}
<div class="row pl-3 ml-1">
<p>Show some information</p>
</div>
{% else %}
<p>There is no data</p>  
{% endif %} 
{% endfor %}
<div />
{% else %}
<p>Please login and register</p>
{% endif %}
{% endblock %}

我用一种不同的方式(也许不那么像蟒蛇(回答了这个问题。

我基本上在python一侧的字段中进行迭代,并使用计数器进行计数。如果数字大于0,那么当我将整数传递到html模板中时,它不会显示消息。

谢谢!

buyer_sched = db.session.query(Buyerschedule).
filter(Buyerschedule.buyer_id == buyer_id).all()
# Iterate through schedule and if all are none, set
# completed to none
completed = 0
for sched in buyer_sched:
print(f'The schedule name is: {sched.id}')
if sched.supplier_id:
completed = completed + 1
print(f'completed is {completed}')
print(f'completed is equal to {completed}')

您可以创建一个自定义的jinja过滤器(https://flask.palletsprojects.com/en/1.1.x/templating/#registering-过滤器(,以检查在for循环之前是否全部为空:

def all_empty(data, key):
return all(not d[key] for d in data)
app.jinja_env.filters['all_empty'] = all_empty

注册后,您可以在模板中调用该函数:

<div class="card-deck" >
{% if data|all_empty('supplier') %}
<p>There is no data</p>
{% else %}
{% for sched in data %}
{% if sched.supplier and sched.supplier.company %}
<div class="row pl-3 ml-1">
<p>{{ sched.supplier.company }}</p>
</div>
{% endif %}
{% endfor %}
{% endif %}
</div>

最新更新