【问题标题】:passing html element using to_html in flask在烧瓶中使用 to_html 传递 html 元素
【发布时间】:2017-11-14 07:39:40
【问题描述】:

我有一个数据框,其中包含一个包含<canvas> something </canvas> 元素的列。在 flask 应用程序中,我使用 df.to_html() 将此数据传递给模板,但它始终无法正常工作,并且始终在显示的 html 表中显示 <canvas>

【问题讨论】:

    标签: python flask


    【解决方案1】:

    要启用在to_html() 方法中显示字符<, >, and & 符号,我们需要将escape 属性更改为False。因为默认情况下 to_html 方法将字符 <, >, and & 转换为 HTML 安全序列。我们还需要在模板文件中使用safe 过滤器来显示表格内的标签。

    由于您已经找到了如何在 Flask 模板中正确显示 HTML,我正在为将来的读者提供一个操作示例。

    app.py 包含一个带有html 标签的数据框,我们要在模板中渲染它:

    import pandas as pd
    from flask import Flask, render_template
    
    def get_panda_data():
        tags = ["<h1>Example header</h1>",
                '<div style="color: red;">Example div</div>',
                '<input type="text" name="example_form" \
    placeholder="Example input form">'
            ]
        pd.set_option('display.max_colwidth', -1)
        tags_frame = pd.DataFrame(tags, columns = ["Tag Example"])
        tags_html = tags_frame.to_html(escape=False)
        return tags_html    
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        html_data = get_panda_data()
        return render_template("dataframe_example.html", html_data = html_data)
    
    if __name__ == '__main__':
        app.run(debug = True)
    

    然后在模板文件dataframe_example.html中,我们可以很容易的展示pandasto_html方法生成的数据表:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Dataframe Flask Example</title>
    </head>
    <body>
        <h1>Dataframe Flask Example</h1>
            {{ html_data | safe }}
    </body>
    </html>
    

    输出如下:

    【讨论】:

      【解决方案2】:

      我意识到我必须使用选项to_html(escape=False) 来解决这个问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-05
        • 2022-10-15
        • 1970-01-01
        • 2022-11-05
        • 2020-12-21
        • 1970-01-01
        • 2021-01-03
        • 2019-01-11
        相关资源
        最近更新 更多