我什么时候应该在 Django 的模板系统中使用 escape 和 safe ?
如果我有一个人们发表评论的框,然后我像这样显示该评论......我应该逃避吗?
{{ c.title }}
If I have a box where people put comments, and then I display that comment like this...should I escape?
{{ c.title }}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
事实上,这取决于。 Django 的模板引擎会自动转义,因此您实际上不需要转义。
如果你像
{{c.title|safe}}
这样添加模板过滤器“safe”,那么你确实需要担心 html 注入之类的事情,因为“safe”将字符串标记为这样,这意味着它不会被逃脱。还有一个 {% autoescape on %}...{% endautoescape %} 模板标记,如果需要,可以将其中的“on”更改为“off”。默认情况下它是打开的并且不需要标签。
其他模板引擎默认情况下可能不会转义,Jinja2就是其中之一。
Actually, it depends. Django's templating engine does escaping automatically, so you don't really need to escape.
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.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.
Other template engines may not be escaping by default, Jinja2 is one of them.
HTML 自动转义默认处于启用状态,因此在大多数情况下您不需要手动转义,但不是全部!
将变量的内容转储到 HTML 元素中是可以的:
Django 会自动转义字符
<
、>
、&
、< code>" 和'
,这就是这里所需要的。将变量转储到属性内也是可以的,因为
"
和'< /code> 都已转义,但请确保记住包含引号,因为空格不会转义:
如果您想在内联 Javascript 中使用字符串,则必须使用
escapejs
过滤器,并且不要'不要忘记引号。这可以防止从 Javascript 变量的引号中转义,也可以防止使用从
标记中转义:
HTML auto-escaping is on by default, so you don't need to manually escape in most cases, but not all!
Dumping the contents of a variable inside an HTML element is fine:
Django will automatically escape the characters
<
,>
,&
,"
and'
, which is what is needed here.It's also OK to dump a variable inside an attribute, since
"
and'
are both escaped, but make sure you remember to include quotes, as spaces are not escaped:If you want to use a string inside inline Javascript, you must use the
escapejs
filter, and don't forget the quotes. This protects against both escaping out of the quotes for the Javascript variable, and escaping out of the<script>
tag using</script>
:是的!如果他们输入
作为标题会怎样?
Django 自动转义使这变得更容易。
Yes! What if they entered
<script>alert('boom');</script>
as the title?Django autoescape makes this much easier.
django 模板中默认启用自动转义,因此您不需要使用转义。当您想要关闭它并让模板渲染系统知道您的日期以未转义的形式是安全的时,可以使用安全。有关详细信息,请参阅 django 文档:
Auto-escaping is on by default in django templates, so you don't need to use escape. Safe is used when you want to turn it off and let the template rendering system know that your date is safe in an un-escaped form. See the django docs for details: