在我的 django 应用程序中,我使用模板来构建电子邮件正文,其中一个参数是 url,请注意 url 中有两个参数以“&”分隔。
t = loader.get_template("sometemplate")
c = Context({
'foo': 'bar',
'url': 'http://127.0.0.1/test?a=1&b=2',
})
print t.render(c)
渲染后会产生:http://127.0.0.1/test?a=1&b=2
请注意,& 符号在 HTML 中编码为“&”。解决该问题的一种方法是将每个参数单独传递给我的模板并在模板中构造 url,但我想避免这样做。
有没有办法禁用上下文参数的 HTML 编码或至少避免对 & 符号进行编码?
要针对单个变量关闭它,请使用mark_safe
:
from django.utils.safestring import mark_safe
t = loader.get_template("sometemplate")
c = Context({
'foo': 'bar',
'url': mark_safe('http://127.0.0.1/test?a=1&b=2'),
})
print t.render(c)
或者,要完全关闭 Python 代码的自动转义,use the autoescape初始化时的参数Context http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#auto-escaping-considerations:
c = Context({
'foo': 'bar',
'url': 'http://127.0.0.1/test?a=1&b=2',
}, autoescape=False)
The 如何关闭[自动 HTML 转义] http://docs.djangoproject.com/en/dev/topics/templates/#how-to-turn-it-off如果您愿意的话,文档的部分涵盖了一些模板内选项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)