You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:45:03