开发者社区 问答 正文

Flask:将dataframe作为html处理的render_template

我正在使用以下代码将数据帧值呈现为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

展开
收起
is大龙 2020-03-24 10:07:48 1026 分享 版权
1 条回答
写回答
取消 提交回答
  • 好的,首先要注意的是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

    2020-03-24 10:07:56
    赞同 展开评论
问答分类:
问答地址: