[python] 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 <"'> are converted to html entities. How can I disable that so that the HTML renders correctly?

This question is related to python jinja2 flask

The answer is


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 ) }}

For handling line-breaks specifically, I tried a number of options before finally settling for this:

{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
  {% if not loop.last %}
  <br/>
  {% endif %}
{% endfor %}

The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.

Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split function) and also doesn't add an unnecesssary <br/> after the last item.


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.


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 %}

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to jinja2

'if' statement in jinja2 template Ansible: filter a list by its attributes Split string into list in jinja? How to iterate through a list of dictionaries in Jinja template? How to write dynamic variable in Ansible playbook Jinja2 template not rendering if-elif-else statement properly Jinja2 template variable if None Object set a default value Convert integer to string Jinja Link to Flask static files with url_for How to pass a list from Python, by Jinja2 to JavaScript

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?