23

I'm using Flask in an app that render some data from a sqlite database. My problem is when the app render some text that has html inside, appear as text instead of html. For example, the record in database has the following text:

My tailor <strong>is</strong> rich

The html page render as is:

<html>
<!-- snip .... -->
My tailor &gt;strong&lt;is&gt;/strong&lt; rich
<!-- snip .... -->
</html>

And, what I want is this ("is" word has to be bolder):

<html>
<!-- snip .... -->
My tailor <strong>is</strong> rich
<!-- snip .... -->
</html>

Does anybody know how can I do that?

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
jaloplo
  • 941
  • 2
  • 12
  • 32

2 Answers2

54

If you know the content is safe, simply use the safe filter:

{# In the Jinja template #}
{% for article in articles %}
<div class="article">{{article|safe}}</div>
{% endfor %}
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
0

Another possibility is to use jinja Markup class, just the way safe filter does. This will allow you to render HTML without filtering content through the safe filter. Below is an example of how this can be accomplished.

from jinja2 import Markup, escape

def render_markup():
    return Markup("{0}{1}{2}{3}{4}".format(
        escape("My tailor "), 
        "<strong>", 
        escape("is"), 
        "</strong>", 
        escape(" rich")))

After this you can register your function in the Flask jinja globals, and use it from the jinja template.

app.jinja_env.globals["render_markup"] = render_markup

No safe needed in the template.

<html>
<!-- snip .... -->
{{ render_markup() }}
<!-- snip .... -->
</html>
Boris
  • 2,275
  • 20
  • 21