首页 > 解决方案 > 计算表中的条目数,然后在 html 中使用 jinja 显示

问题描述

我有一个烧瓶应用程序,它从表单中获取数据并将其保存到使用 SQLAlchemy 构建的表中。我正在构建一个仪表板,它将显示一些信息片段,例如表中的总条目。我运行了下面的代码并且没有错误,但没有显示我在 html 中使用 jinja 的位置。

视图.py

#equipment home page
@equipment_blueprint.route('/', methods=['GET','POST'])
def equipment_home():
    #total equipment card
    total_equipment = db.session.query(EquipmentInfo).count()

    return render_template('equipment_base.html')

total_equipment 变量是我试图用来计算 EquipmentInfo 表中的条目的变量。

html

<!-- first bootstrap card -->
<div class="card text-white bg-dark mb-3" style="max-width: 18rem;">
<div class="card-header">Header</div>
<div class="card-body">
    <h5 class="card-title">Dark card title {{ total_equipment }} </h5>
    <p class="card-text">Some quick example text to build on the card title 
    and make up the bulk of the card's content.</p>
</div>
</div>

我尝试将 {{ total_equipment }} 插入到 html 中。还有另一种可行的方法吗?我只是将它输入到标题中以进行测试,看看这是否有效。

标签: pythonflaskjinja2

解决方案


您需要向 提供模板变量的名称和值render_template,如下所示:

return render_template('equipment_base.html', total_equipment=total_equipment)

请参阅此处的文档。


推荐阅读