2

在视图代码中呈现模板时(例如电子邮件),有什么方法可以完全关闭 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)

If customer.nameis something like "Jack & Jill" - 主题看起来像 "Hi Jack &\amp; Jill"(没有反斜杠!)

有没有类似的东西

subject = subject_template.render(context, autoescape=False)

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

4

5 回答 5

6

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

像这样的东西:

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

    Nor this: {{ other_data }}
    {% autoescape on %}
        Auto-escaping applies again: {{ name }}
    {% endautoescape %}
{% endautoescape %}
于 2013-08-20T22:20:45.753 回答
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)

虽然,在模板本身内部控制什么是安全的或不安全的更好,这就是为什么autoescape应该优先使用 using 的原因。

于 2013-08-20T22:23:03.903 回答
0

这是未经测试的,但根据源代码审查,看起来上下文对象可以autoescape作为键。

context = Context({'customer':MyCustomerModel.objects.get(pk=1), 'autoescape': False})
subject = subject_template.render(context)

也就是说,这是一个相当彻底的变化。如果您知道模板可能正在寻找什么值,最好使用mark_safe这些值并传入预定义的选项。这将具有额外的好处,即不会冒客户端模板调用对客户有副作用的方法的可能性。第一次有人编写模板并放入时{{ customer.delete }},您会遇到问题。

于 2013-08-20T22:24:25.623 回答
0

使用 Django 的自动转义标签:

{% autoescape off %}
    {{ body }}
{% endautoescape %}

有关更多信息,请查看此处的文档。

于 2013-08-20T22:21:05.983 回答
0

刚回来用一个简单的解决方案回答我自己的问题,已经有 4 个答案.. 谢谢。

这就是我所做的:

subject_template = Template(u'{%% autoescape off %%}%s{%% endautoescape %%}' % email.subject)

于 2013-08-20T22:29:35.217 回答