Passing HTML to template using Flask/Jinja2

When you have a lot of variables that don't need escaping, you can use an autoescape override block:

{% autoescape false %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}

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.


From the Jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

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

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.