gpt4 book ai didi

python - 在flask中使用to_html传递html元素

转载 作者:行者123 更新时间:2023-12-01 02:27:05 25 4
gpt4 key购买 nike

我有一个数据框,其中包含一列 <canvas> something </canvas>元素。在 flask应用程序中,我使用 df.to_html() 将此数据传递到模板,但它从来没有工作,并且总是显示 <canvas>在显示的 html 表中。

I intend to let the canvas element be captured by a <code>chartjs</code> function

最佳答案

启用显示字符 <, >, and &登录to_html()方法,我们需要更改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我们可以轻松展示pandas生成的数据表to_html方法:

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

输出如下:

dataframe_template_html

关于python - 在flask中使用to_html传递html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47280146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com