【发布时间】:2020-07-16 19:07:51
【问题描述】:
假设我使用 SQLAlchemy 创建了一个如下所示的表:
Table
+----+------+------+------+-----+
| id | Col1 | Col2 | Col3 | foo | ...
+----+------+------+------+-----+
| 1 | a | b | c | bar | ...
+----+------+------+------+-----+
.
.
.
我正在使用 python flask 来渲染一个 html 模板。
假设我使用flask 的render_template 方法将此表的一行传递给我的html 模板。
return render_template('foo'.html, row=Table.query.filter_by(id=1).first())
然后在foo.html 中,我想遍历这一行并访问以col 开头的每一列的值。
换句话说,我只想访问a,b,c,而不是bar。
我试过了:
{% for i in range(1,3) %}
{{ row.coli }}
{% endfor %}
但是这不起作用。
我怎样才能做到这一点?
【问题讨论】:
-
您好,我尝试添加
{{ getattr(row, 'col' + str(i)) }},但收到错误jinja2.exceptions.UndefinedError: 'str' is undefined。有什么想法吗? -
如果你知道这些列,你不妨直接使用它们,即写
{{ row.Col1 }},然后写{{ row.Col2}},等等(如果使用Core,则写{{ row.c.Col1 }})。
标签: python html flask sqlalchemy flask-sqlalchemy