我有一个数据框,其中包含一列 <canvas> something </canvas>
元素。在 flask
应用程序中,我使用 df.to_html()
将此数据传递到模板,但它从来没有工作,并且总是显示 <canvas>
在显示的 html 表中。
最佳答案
启用显示字符 <, >, 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>
输出如下:
关于python - 在flask中使用to_html传递html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47280146/