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

Jinja模板循环中指定渲染对应DataFrame表格的问题

解决Flask模板中分别渲染指定DataFrame表格的问题

我在Flask中通过以下代码将两个DataFrame转换为HTML表格传递至模板:

return render_template('rankings.html', tables=[df1.to_html(index=False, classes='data'), df2.to_html(index=False, classes='data')], titles=['hof','recent'])

希望在模板的左右分栏中分别渲染第一个和第二个表格,但当前Jinja循环会将两个表格堆叠显示。尝试用table[1]等方式访问时仅得到单个字符,迭代方法无效,求正确实现方案。当前模板代码:

<html> 
<head>
<title>Test</title> 
<style>
.tab {
display: inline-block;
margin-left: 4em;
}
body {
background-image: linear-gradient(to bottom right, red, white);
}
.column {
display:inline-block;
width:50%;
float:left;
}
</style>
</head> 
<body><center>
<div class="column"><p><h2>Hall of fame</h2></p>{% for table in tables %}{{ table|safe }}{% endfor %}</div>
<div class="column"><p><h2>Most recent</h2></p>{% for table in tables %}{{ table|safe }}{% endfor %}</div>   
</center></body>
</html>

核心问题分析

  1. 循环逻辑错误:当前每个分栏都遍历整个tables列表,导致每个栏都会渲染两个表格,出现堆叠。
  2. 索引访问错误:你尝试的table[1]是访问循环变量table(字符串类型)的第二个字符,而非tables列表的第二个元素,正确写法是tables[1]。

修正方案

方案一:直接通过列表索引指定表格

直接在两个分栏中分别调用tables列表的第0和第1个元素,去掉多余的循环:

<html> 
<head>
<title>Test</title> 
<style>
.tab {
display: inline-block;
margin-left: 4em;
}
body {
background-image: linear-gradient(to bottom right, red, white);
}
.column {
display:inline-block;
width:50%;
float:left;
}
</style>
</head> 
<body>
<div class="column">
    <h2>Hall of fame</h2>
    {{ tables[0]|safe }}
</div>
<div class="column">
    <h2>Most recent</h2>
    {{ tables[1]|safe }}
</div>
<!-- 清除浮动,避免后续布局问题 -->
<div style="clear: both;"></div>
</body>
</html>

方案二:配对标题与表格(更易扩展)

如果未来需要添加更多表格,可在视图函数中将标题和表格打包成元组列表,再在模板中循环渲染:

视图函数修改:

table_pairs = list(zip(titles, [df1.to_html(index=False, classes='data'), df2.to_html(index=False, classes='data')]))
return render_template('rankings.html', table_pairs=table_pairs)

模板修改:

<html> 
<head>
<title>Test</title> 
<style>
.tab {
display: inline-block;
margin-left: 4em;
}
body {
background-image: linear-gradient(to bottom right, red, white);
}
.column {
display:inline-block;
width:50%;
float:left;
}
</style>
</head> 
<body>
{% for title, table in table_pairs %}
<div class="column">
    <h2>{{ title|capitalize }}</h2>
    {{ table|safe }}
</div>
{% endfor %}
<div style="clear: both;"></div>
</body>
</html>

关键说明

  • |safe过滤器必须保留:DataFrame的to_html()生成的是HTML字符串,Jinja默认会转义特殊字符,加上|safe才能让浏览器正确解析为表格。
  • 清除浮动:添加<div style="clear: both;"></div>可以避免浮动元素对后续页面布局的影响。

内容的提问来源于stack exchange,提问作者notanothercliche

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:47:33