在Django的模板系统中什么时候应该使用escape和safe?

问题描述:

如果我有一个人们发表评论的框,然后我显示这样的评论,我应该逃跑吗?

If I have a box where people put comments, and then I display that comment like this...should I escape?

{{ c.title }}


这取决于。 Django的模板引擎会自动转义,所以你真的不需要逃脱。

Actually, it depends. Django's templating engine does escaping automatically, so you don't really need to escape.

如果您添加模板过滤器safe,如 {{c .title | safe}} 那么你确实需要担心像html注入这样的事情,因为安全标记字符串,这意味着它不会被转义。

If you add template filter "safe" like {{c.title|safe}} then you do need to worry about things like html injection, because "safe" marks the string as such and it means that it won't be escaped.

还有一个{%autoescape on%} ... {%endautoescape%}模板标签,其中on可以更改为off,如有必要。默认情况下,该标签是不需要的。

There is also an {% autoescape on %}...{% endautoescape %} template tag, where "on" can be changed to "off", if necessary. By default it's on and the tag is not needed.

默认情况下,其他模板引擎可能无法转义,Jinja2是其中之一。

Other template engines may not be escaping by default, Jinja2 is one of them.