【问题标题】:How do I show an HTML message with Flask if the Jinja for loop returns nothing如果 Jinja for 循环不返回任何内容,我如何使用 Flask 显示 HTML 消息
【发布时间】:2020-09-17 03:08:04
【问题描述】:

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

假设表有 5 个条目并且没有字段存在,在我当前的代码中发生的情况是我看到我的消息 5 次。

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

ma​​in.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 %}

我以不同的方式回答了这个问题(也许不是那么 Pythonic)。

我基本上遍历了 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}')

【问题讨论】:

    标签: html python-3.x flask jinja2


    【解决方案1】:

    您可以创建一个自定义 jinja 过滤器 (https://flask.palletsprojects.com/en/1.1.x/templating/#registering-filters) 来检查 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>
    

    【讨论】:

    • 谢谢你。我感谢您的帮助。我对此不太熟悉,所以我正在研究它。
    猜你喜欢
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2021-12-10
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多