python - 如何防止 Django 模板中的自动转义?

标签 python django templates escaping

在文档中说:

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."

“填充变量”部分如何工作?我实际上正在寻找一种在 View 中将模板标记声明为安全的方法。不知何故,我认为让设计师来决定并不是一个好主意。只要她“认为”这是个好主意,我的同事就会添加它。

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs

最佳答案

Django 有一个名为 safe 字符串的字符串子类(特别是 SafeUnicodeSafeString),可以使用 django 创建。 utils.safestring.mark_safe。当模板引擎遇到安全字符串时,它不会对其执行 HTML 转义:

>>> from django.utils.safestring import mark_safe
>>> from django.template import Template, Context
>>> Template("{{ name }}").render(Context({'name': mark_safe('<b>Brad</b>')}))
u"<b>Brad</b>"

如果您正在编写自己的模板标签,则需要实现 render(),它将返回一个被视为安全的字符串,这意味着您必须自己处理任何必要的转义。但是,如果您正在编写模板过滤器,则可以在过滤器上设置属性 is_safe = True 以避免自动转义返回值,例如

@register.filter
def myfilter(value):
    return value
myfilter.is_safe = True

参见 https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#filters-and-auto-escaping了解更多详情。

关于python - 如何防止 Django 模板中的自动转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774902/

相关文章:

amazon-web-services - 是否可以创建 AWS CloudFormation 模板,该模板将创建一个状态为 CREATE_FAILED 的堆栈

python - 如何重置 QGridLayout 中小部件的列跨度?

python - 如何连接列表中的项目?

python - 以 3D 形式绘制分段函数

Django 管理员登录不重定向

c++ - operator<< 不能使用其 friend 数组的 IT 成员

c++ - 带有 const 限定符的类型推导失败

python - 如何使用 python 解码 SSL 证书?

python - Django "Running migrations": django. db.utils.OperationalError : (2013, 'Lost connection to MySQL server during query' 期间出错)

python - 如何在django中设置excel文件的路径