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

e.g.

{{ user.username|e }}

Pipe it through the |e filter

Jinja: Template Designer Documentation -> HTML Escaping


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;'

You could also tell the environment to autoescape everything:

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

note: in jinja1 this is auto_escape


Flask has a built in tojson filter:

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