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
You can also declare it HTML safe from the code:
from flask import Markup
value = Markup('<strong>The HTML String</strong>')
Then pass that value to the templates and they don't have to |safe
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>
Some people seem to turn autoescape off which carries security risks to manipulate the string display.
If you only want to insert some linebreaks into a string and convert the linebreaks into <br />
, then you could take a jinja macro like:
{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}
and in your template just call this with
{{ linebreaks_for_string( my_string_in_a_variable ) }}
the ideal way is to
{{ something|safe }}
than completely turning off auto escaping.
When you have a lot of variables that don't need escaping, you can use an autoescape
block:
{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}