如何防止 Django 模板中的自动转义?
在文档中它说:
唯一的例外是已经被标记为“安全”且无法转义的变量,无论是通过填充变量的代码,还是因为它应用了安全或转义过滤器。”
“填充变量”部分如何工作?实际上,我正在寻找一种方法来声明模板标签在视图中是安全的,我认为让设计师决定并不是一个好主意,只要她“认为”这是一个好主意,她就会添加它。
<一href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/模板/内置/?from=olddocs
In the docs it says:
The only exceptions are variables that are already marked as “safe” from escaping, either by the code that populated the variable, or because it has had the safe or escape filters applied."
How does the "populated the variable" part work ? I'm actually looking for a way to declare a template tag as safe in the view. I somehow think it's not a good idea to let a designer decide. My co-worker will just add it whenever she 'thinks' it's a good idea.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django 有一个字符串子类,称为安全字符串(具体为
SafeUnicode
或SafeString
),可以使用django.utils.safestring 创建.mark_safe
。当模板引擎遇到安全字符串时,它不会对其执行 HTML 转义:如果您正在编写自己的模板标记,则需要实现
render()
,它将返回一个字符串,该字符串将被视为安全,这意味着您必须自己处理任何必要的逃生。但是,如果您正在编写模板过滤器,则可以在过滤器上设置属性is_safe = True
以避免返回值自动转义,例如请参阅 https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#filters-and-auto-escaping 了解更多详细信息。
Django has a subclass of strings called safe strings (specifically
SafeUnicode
orSafeString
), which can be created usingdjango.utils.safestring.mark_safe
. When the template engine comes across a safe string it doesn't perform HTML escaping on it:If you're writing your own template tag, you need to implement
render()
which will return a string that will be treated as safe, meaning you have to handle any escaping necessary yourself. However if you're writing a template filter, you can set the attributeis_safe = True
on the filter to avoid auto escaping of the returned value, e.g.See https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#filters-and-auto-escaping for more details.
您可以调用 django.utils.safestring.mark_safe 并
在模板中传递变量,它将在不转义的情况下打印(将弹出警报)。虽然自动转义确实是一个很棒的功能,可以让您避免一些糟糕的事情。
You could call
django.utils.safestring.mark_safe
and pass you variableIn template it will be printed without escaping (alert will popup). Though auto-escape is really a great feature that will save you from some bad things.