django - 如何阻止django模板代码转义

标签 django django-templates

在 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/

相关文章:

python - Django ORM - 获取N个随机记录,然后将它们分成2组

python - Django : unique name for object within foreign-key set

django - NoReverseMatch : Unable to pass parameter from template to view.

django - Ajax ,Django : status 200 but throws error instead of success

django - 导入错误: cannot import name 'six' from 'django.utils'

django - Django Haystack Solr-Solr的推荐位置和目录结构

mysql - 生产环境频繁Mysql gone away (Error 2006)

erlang - 使用 Erlydtl 进行主/应用程序布局

django - 如何在 POST 请求后返回重定向到 Django 中的上一页

python - Django 模板标签 {{ form.my_field_xxx }}