jinja2: html escape variables

孤人 提交于 2019-12-03 04:50:01
jitter

e.g.

{{ user.username|e }}

Pipe it through the |e filter

Jinja: Template Designer Documentation -> HTML Escaping

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!