Reputation: 273502
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?
Upvotes: 40
Views: 43219
Reputation: 54605
e.g.
{{ user.username|e }}
Pipe it through the |e
filter
Docs:
Upvotes: 66
Reputation: 1
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("<","< ;")
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 :P
Then use jinja2 to print out the formatted string. The < should appear in your display.
Upvotes: -3
Reputation: 43804
Flask has a built in tojson
filter:
http://flask.pocoo.org/docs/templating/#standard-filters
Upvotes: 1
Reputation: 3330
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'<script>alert("yy")</script>')
>>> str(jinja2.escape(a))
'<script>alert("yy")</script>'
Upvotes: 11
Reputation: 1638
You could also tell the environment to autoescape everything:
e = Environment(loader=fileloader, autoescape=True)
note: in jinja1 this is auto_escape
Upvotes: 25