Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid auto escaping HTML tags with Jinja2

I have flask, jinja2 and python.
So, I'm trying to display text that is stored as markdown.
I do this

class Article(db.Entity):
...

    def html(self):
        return markdown(self.text) # from markdown import markdown

Next in my view I do this

html_text = article_.html()    
return render_template('article.html', article=article_, comments=comments, user=user, text=html_text)

And in article.html I just have this line

{{text}}

So, with data stored in db as *im busy* I have <p><em>im busy</em></p> in my browser. I tried to use .replace('&lt;', '<').replace('&gt;', '>') but it changes nothing.

like image 576
sashaaero Avatar asked Mar 10 '17 06:03

sashaaero


People also ask

Does Jinja escape HTML?

Escaping everything except for safe values will also mean that Jinja is escaping variables known to not include HTML (e.g. numbers, booleans) which can be a huge performance hit. The information about the safety of a variable is very fragile.

What is auto escaping HTML?

Auto Escape is an optional mode of execution in the Template System developed to provide a better defense against cross-site scripting (XSS) in web applications.

How do you escape characters in jinja2?

To escape jinja2 syntax in a jinja2 template with Python Flask, we can put render the template code without interpretation by putting the code in the {% raw %} block.

What is Autoescape Jinja?

When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.


1 Answers

Do you know safe filter?

{{text|safe}}

Passing HTML to template using Flask/Jinja2

like image 91
klim Avatar answered Oct 05 '22 22:10

klim