是否可以将两个数据帧发送到我的html(烧瓶)?

时间:2019-12-20 12:51:41

标签: python html flask

所以我的html页面收到一个pandas数据框。

return render_template('example.html', tables=[data_frame.to_html(classes='data')], titles=dataframe.columns.values)

我的html页面显示它:

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}

我想做的是在我的html页面中显示两个单独的数据框。我该怎么办?

例如: 如果我有数据帧df1和df2,

在html页面中,我想在一些文本后显示它们。

show df1

<h2> some text </h2>

show df2

2 个答案:

答案 0 :(得分:2)

由于render_template接受字典,因此可以使用“表”和“标题”键将名为context的Dict对象传递给“ render_template”函数。 然后在您的Jinja中,您可以通过context.tablecontext.title访问这些密钥。

示例:

def my_function(request):
    ...
    get your dataframe
    ...
    context = {"tables":[data_frame.to_html(classes='data')],
               "titles" : dataframe.columns.values,
              }

    return render_template('template.html', context=context)

答案 1 :(得分:0)

这可以在 render_template

中轻松完成

您的代码可以这样更改:

return render_template('example.html',tables= [data_frame1.to_html(classes='data'),data_frame2.to_html(classes='data')], 
titles=['na','FirstTable','SecondTable'])

如您所见,您可以在表中添加多个数据框。

现在在Jinja中,您可以简单地遍历每个表(数据框)并显示

{% for table in tables %}
{{ titles[loop.index] }}
{{ table|safe }}
{% endfor %}

请参考下图供您参考:

Sample image for your reference