如何防止Django模板中的自动转义? [英] How to prevent auto escape in Django templates?

查看:108
本文介绍了如何防止Django模板中的自动转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文档中,它说:


唯一的例外是已经被标记为安全的变量,代码填充变量,或者因为它已经应用了安全或逃避过滤器。

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

推荐答案

Django有一个名为安全字符串的字符串(具体 SafeUnicode SafeString ),可以使用 django.utils.safestrin创建g.mark_safe 。当模板引擎遇到安全的字符串时,它不会执行HTML转义:

Django has a subclass of strings called safe strings (specifically SafeUnicode or SafeString), which can be created using django.utils.safestring.mark_safe. When the template engine comes across a safe string it doesn't perform HTML escaping on it:

>>> 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 ,以避免自动转义返回值,例如

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 attribute is_safe = True on the filter to avoid auto escaping of the returned value, e.g.

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

请参阅 https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping 有关详情。

这篇关于如何防止Django模板中的自动转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆