在烧瓶中使用to_html传递html元素 [英] passing html element using to_html in flask
问题描述
我有一个数据框,其中包含一个包含< canvas>的列.</canvas>
元素.在 flask
应用程序中,我使用 df.to_html()
将此数据传递到模板,但是它从未起作用,并且始终显示< canvas>
在显示的html表中.
I have a dataframe that contains a column containing <canvas> something </canvas>
element. In a flask
application, I passed this data to a template using df.to_html()
, but it never is working and always shows the <canvas>
within displayed html table.
推荐答案
要在 to_html()
中启用显示字符<,>和&
的符号方法,我们需要将 escape
属性更改为 False
.因为默认情况下, to_html
方法将字符< ;、>和&
转换为HTML安全序列.另外,我们需要在模板文件中使用 safe
过滤器以在表格内显示标签.
To enable showing the characters <, >, and &
signs in to_html()
method, we need to change the escape
attribute to False
. Because by default to_html
method converts the characters <, >, and &
to HTML-safe sequences. Also we need to use safe
filter in the template file to show the tags inside the table.
您已经找到了如何在Flask模板中正确显示HTML的方法,我在此为以后的读者提供该操作的示例.
As you have already found how to show the HTML properly in Flask template, I am giving an example of the operation for future readers.
app.py
包含一个带有 html
标记的数据框,我们希望在模板中对其进行渲染:
app.py
contains a dataframe with html
tags which we want to render in the template:
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
)中,我们可以轻松显示熊猫 to_html
方法生成的数据表:
Then in template file which is dataframe_example.html
we can easily show the data table generated by pandas to_html
method:
<!DOCTYPE html>
<html>
<head>
<title>Dataframe Flask Example</title>
</head>
<body>
<h1>Dataframe Flask Example</h1>
{{ html_data | safe }}
</body>
</html>
输出看起来像:
这篇关于在烧瓶中使用to_html传递html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!