如何阻止 django 模板代码转义

Guy*_*den 2 django django-templates

在视图代码中呈现模板时,有什么方法可以完全关闭 django auto_escaping(例如,对于电子邮件):

from django.template import Context, Template
subject_template_string = "Hi {{ customer.name }}"
subject_template = Template(subject)
context = Context({'customer':MyCustomerModel.objects.get(pk=1)})
subject = subject_template.render(context)
Run Code Online (Sandbox Code Playgroud)

如果customer.name类似于“Jack & Jill”——主题看起来像“Hi Jack &\amp; Jill”(没有反斜杠!)

有没有像

subject = subject_template.render(context, autoescape=False)
Run Code Online (Sandbox Code Playgroud)

编辑:实际模板是由客户端在数据库中创建的,我希望避免不得不说添加|safe到可能发生这种情况的所有模板中...

Wol*_*lph 6

全局禁用它通常是一个坏主意,因为您很容易忘记它。我建议使用 templatetag 来为模板的那部分禁用它。

像这样的东西:

{% autoescape off %}
    This will not be auto-escaped: {{ data }}.

    Nor this: {{ other_data }}
    {% autoescape on %}
        Auto-escaping applies again: {{ name }}
    {% endautoescape %}
{% endautoescape %}
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 6

如何使用mark_safe

为 (HTML) 输出目的显式地将字符串标记为安全。返回的对象可以在任何适合字符串或 unicode 对象的地方使用。

它将字符串标记为安全,因此,您应该customer.name取出并传递给模板:

from django.utils.safestring import mark_safe
customer = MyCustomerModel.objects.get(pk=1)
context = Context({'customer_name': mark_safe(customer.name)})
subject = subject_template.render(context)
Run Code Online (Sandbox Code Playgroud)

虽然,控制什么是安全的最好在模板内部做,这就是为什么autoescape应该优先使用。