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

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

本文介绍了我什么时候应该在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 注入之类的事情,因为safe"将字符串标记为这样并且这意味着它不会被转义.

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.

这篇关于我什么时候应该在Django的模板系统中使用escape和safe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:37