在 View 代码(例如电子邮件)中呈现模板时,是否有任何方法可以完全关闭 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)
如果 customer.name
类似于“Jack & Jill”——主题看起来像“Hi Jack &\amp; Jill”(没有反斜杠!)
有没有类似的东西
subject = subject_template.render(context, autoescape=False)
编辑:实际模板是由客户端在数据库中创建的,我希望避免在可能发生这种情况的所有模板中添加 |safe
...
最佳答案
全局禁用它通常不是一个好主意,因为您很容易忘记它。我会建议使用 templatetag 来为模板的那部分禁用它。
像这样:
{% autoescape off %}
This will not be auto-escaped: {{ data }}.
Nor this: {{ other_data }}
{% autoescape on %}
Auto-escaping applies again: {{ name }}
{% endautoescape %}
{% endautoescape %}
关于django - 如何阻止django模板代码转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345867/