我正在使用以下代码将数据帧值呈现为HTML,并将其定向为HTML,并且工作正常。
@app.route('/index/')
def index():
return render_template('index.html',tables=[df.head().to_html(classes='table table-striped') ] ,titles=df.columns.values )
我确实有另一个数据框需要在相同的'index.html'中使用。我试图在上面的代码中添加相同的内容,如下所示
@app.route('/index/')
def index():
return render_template('index.html',tables=[df.head().to_html(classes='table table-striped'),\*dfrme.head().to_html(classes='table1')\* ] ,titles=df.columns.values )
它使桌子一个接一个。因为我希望其他dataframe值在index.html的不同区域中调用,所以需要您的帮助来实现相同的目的。
渲染的代码:
<table class="w3-table w3-striped w3-border">
<tr>
{% for table in tables %}
{{ table|safe }}
{% endfor %}
</tr>
</table>
问题来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
好的,首先要注意的是DataFrame.to_html
函数会生成完整表,因此无需放置外部`
模板中的`标签。
我将通过创建一个函数来实现此目的,该函数返回要在模板中使用的字典:
from flask import Flask, render_template
app = Flask(__name__)
# Just define this once
classes = 'w3-table w3-striped w3-border'
def gen_dict(df, title):
return {'title': title,
'table': df.head().to_html(classes=classes)
}
然后在您的路由中,以例如df和dfrme作为两个数据帧,创建一个嵌套字典,然后将其与dict拆包一起传递给render_template函数:
@app.route('/')
def index():
d = {'df1': gen_dict(df, 'First Dataframe'),
'df2': gen_dict(dfrme, 'Second Dataframe')
}
return render_template('index.html', \*d)
然后,您可以在模板中分别显示每个表以及标题:
<h1> {{df1.title}} </h1>
{{df1.table|safe}}
Some where else...
<h1> {{df2.title}} </h1>
{{df2.table|safe}}
将来添加更多的数据帧,然后成为向d字典添加相似的键/值对并编辑模板代码的情况。
回答来源:stackoverflow