How do I html-escape dangerous unsanitized input in jinja2?

Question:

Can I do it inside the template or must it be done in python code?

I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2?

Asked By: flybywire

||

Answers:

e.g.

{{ user.username|e }}

Pipe it through the |e filter

Jinja: Template Designer Documentation -> HTML Escaping

Answered By: jitter

You could also tell the environment to autoescape everything:

e = Environment(loader=fileloader, autoescape=True)

note: in jinja1 this is auto_escape

Answered By: Jeroen Dierckx

If you want to escape html in your programme, you can do it like this(example):

>>> import jinja2
>>> jinja2.__version__
'2.6'
>>> a
'<script>alert("yy")</script>'
>>> jinja2.escape(a)
Markup(u'&lt;script&gt;alert(&#34;yy&#34;)&lt;/script&gt;')
>>> str(jinja2.escape(a))
'&lt;script&gt;alert(&#34;yy&#34;)&lt;/script&gt;'
Answered By: jianpx

Flask has a built in tojson filter:

http://flask.pocoo.org/docs/templating/#standard-filters

Answered By: philfreo

You can do a string check and replace with the corresponding escaped characters.

For example: string=I am a special character <
Do the following:

string.replace("<","&lt ;")

Note that in your code, the space between t and ; has been eliminated. Can’t eliminate this here as it will be formatted to show < instead 😛

Then use jinja2 to print out the formatted string. The < should appear in your display.

Answered By: Huey Eng
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.