Reputation: 179
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.
Upvotes: 0
Views: 4888
Reputation: 13651
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.
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
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)
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>
The output looks like:
Upvotes: 3
Reputation: 179
I realized that I had to utilize the option to_html(escape=False)
to solve this problem
Upvotes: 0