【问题标题】:How to disable autoescape when using django template from_string() and render()?使用 django 模板 from_string() 和 render() 时如何禁用自动转义?
【发布时间】:2020-11-28 16:43:18
【问题描述】:

我正在使用 django-post_office 发送电子邮件,它使用 django 模板呈现主题行:

subject = engine.from_string(self.template.html_content).render(self.context)

为了安全起见,Django 模板自动 sets autoescape=True,这意味着如果您有一个 HTML 字符,例如 Here's an email,它将生成一个带有转义字符的字符串:Here's an email

如何在使用from_stringrender 以正确显示电子邮件主题时禁用自动转义?

另一个例子:

from django.template import engines
template = engines['django'].from_string("My name is {{ my_name }}.")
context = {"my_name": "<FooBar's>"}
print(template.render(context))

结果:

My name is &lt;FooBar&#x27;s&gt;.

【问题讨论】:

  • 你能把autoescape的引擎选项改成false吗?
  • @ha-neul 可以,但你如何只为这一个变量做到这一点?
  • docs.djangoproject.com/en/3.1/topics/templates,搜索engine,它说:DjangoTemplates engines accept the following OPTIONS: 你在'OPTIONS' 中将其更改为False
  • 是的,但这需要完全重置模板引擎,这是一个安全风险。在这种情况下我该怎么做?
  • 只是一个想法:也许定义一个custom_from_string 函数可以解决你的问题

标签: django django-templates django-postoffice


【解决方案1】:

您可能只想使用正确的autoescape 模板标签来转义字符串

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

或将其标记为safe

"My name is {{ my_name|safe }}.

您也可以通过将engine.autoescape 设置为 False 来进行转义

【讨论】:

  • 谢谢,我想我可以申请.from_string("{% autoescape off %}My name is {{ my_name }}.{% endautoescape %}"),但感觉不是很pythonic。有没有一种方法可以在不更改整个引擎的标志的情况下将标志传递给这个模板的构造函数?
  • 你为什么不把变量标记为安全,显式比隐式好
猜你喜欢
  • 2019-08-16
  • 2010-12-08
  • 2012-02-05
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多