Question

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

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

Was it helpful?

Solution

e.g.

{{ user.username|e }}

Pipe it through the |e filter

Jinija: Template Designer Documentation -> Builtin Filters: Escape

OTHER TIPS

You could also tell the environment to autoescape everything:

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

note: in jinja1 this is auto_escape

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

Flask has a built in tojson filter:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top