Passing HTML to template using Flask/Jinja2 Passing HTML to template using Flask/Jinja2 python python

Passing HTML to template using Flask/Jinja2


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.


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 Markupvalue = Markup('<strong>The HTML String</strong>')

Pass that to the templates and you don't have to use the |safe filter on it.


From the Jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by defaultexcept for values explicitly marked as safe. Those can either bemarked by the application or in the template by using the |safefilter.

Example:

 <div class="info">   {{data.email_content|safe}} </div>