如何在Flask渲染的表格中引用行内元组元素添加对应静态图片
Flask 模板遍历嵌套元组拼接图片路径问题解决
问题背景
遍历嵌套元组时,需要在Flask返回的表格中新增一列,展示static文件夹中与内层元组第一个元素同名的图片。
原有实现代码
app.py
@app.route("/output") heading = ("smiles", "calculation_output") data = ( ("smilesA", float), ("smilesB", float), ("smilesC", float) ) return render_template("output.html", heading=heading, data=data)
错误的模板代码(output.html)
<table border="1"> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %}<th>Image</th> </tr> {% for row in data %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} <td><img src="{{ url_for('static', filename='images/' + {{cell[0]}})}}"></td> </tr> {% endfor %} </table>
错误点说明
- Jinja2语法不允许在
{{ }}表达式内部再嵌套一层{{ }} - 内层循环的
cell是当前行的单个元素,无法通过cell[0]获取当前行第一个元素,需要使用外层循环的row变量取row[0] - 缺少图片文件后缀(示例补充
.png,可根据实际文件格式调整)
修正后的模板代码
<table border="1"> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %}<th>Image</th> </tr> {% for row in data %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} <td><img src="{{ url_for('static', filename='images/' + row[0] + '.png')}}"></td> </tr> {% endfor %} </table>
内容的提问来源于stack exchange,提问作者Erik Vik
相关产品推荐
相关产品推荐

