【发布时间】:2018-10-01 15:25:53
【问题描述】:
我在后端使用 Flask 应用程序,它应该使用 Jinja2 模板内的循环在前端呈现 SKU(库存单位)代码列表。 SKU类如下:
class SKU:
"""Class to hold SKU data returned from the database."""
def __init__(self, sku, scanned_at, actual_count, expected_count):
"""Initialize the SKU class with relevant attributes."""
self.sku = str(sku)
self.scanned_at = str(scanned_at)
self.actual_count = int(actual_count)
self.expected_count = int(expected_count)
def get_progress(self):
"""Get the SKU production progress as a percentage."""
return ((self.actual_count / self.expected_count) *
100 if self.expected_count != 0 else 0)
我有一个方法get_all_skus_today(),它返回数据库中今天日期的所有行,作为SKU 对象的列表。当有人使用以下路由访问/skus 时,我想渲染它:
@app.route("/skus")
def skus():
"""Get all SKUs for the day and render the skus.html template."""
skus = get_all_skus_today()
return render_template("skus.html", skus=skus)
问题是我要显示进度值,也就是函数get_progress()的返回,不是Class属性,而是方法。我想做这样的事情:
{% for sku_row in skus %}
{{ sku_row.sku }}
{{ sku_row.get_progress }}
{% endfor %}
但这不起作用。我想避免遍历 SKU 对象列表并将它们转换为元组然后传递给 render_template 函数(这是我之前所做的)。
非常感谢任何帮助 - 如果您需要任何进一步的说明,请告诉我。
【问题讨论】:
标签: python python-3.x flask jinja2