jinja2: html escape variables

℡╲_俬逩灬. 提交于 2019-12-04 10:00:31

问题


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


回答1:


e.g.

{{ user.username|e }}

Pipe it through the |e filter

Jinja: Template Designer Documentation -> HTML Escaping




回答2:


You could also tell the environment to autoescape everything:

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

note: in jinja1 this is auto_escape




回答3:


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



回答4:


Flask has a built in tojson filter:

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



来源:https://stackoverflow.com/questions/1556554/jinja2-html-escape-variables

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