Passing HTML to template using Flask/Jinja2
I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template
. The templating framework seems to escape the HTML automatically, so all <"'>
characters are converted to HTML entities. How can I disable that so that the HTML renders correctly?
Solution 1:
To turn off autoescaping when rendering a value, use the |safe
filter.
{{ something|safe }}
Only do this on data you trust, since rendering untrusted data without escaping is a cross-site scripting vulnerability.
Solution 2:
MarkupSafe provides Jinja's autoescaping behavior. You can import Markup
and use it to declare a value HTML safe from the code:
from markupsafe import Markup
value = Markup('<strong>The HTML String</strong>')
Pass that to the templates and you don't have to use the |safe
filter on it.