如何在django中使用上下文时禁用HTML编码 [英] How to disable HTML encoding when using Context in django

查看:161
本文介绍了如何在django中使用上下文时禁用HTML编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django应用程序中,我正在使用一个模板来构造邮件正文,其中一个参数是url,请注意,在URL中有两个由&号分隔的参数。

In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the 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)

渲染后生成:$ code> http://127.0.0.1/test?a=1&b=2

After rendering it produces: http://127.0.0.1/test?a=1&b=2

请注意,&符号是HTML编码为& amp; amp。解决问题的一个方法是将每个参数分别传递给我的模板,并在模板中构建url,但是我想避免这样做。

Note the ampersand is HTML encoded as "&". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.

有没有方式来禁用上下文参数的HTML编码,或至少避免编码&符号?

Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?

推荐答案

要关闭一个单一的变量,使用 mark_safe

To turn it off for a single variable, use 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代码自动转义,在初始化上下文时使用 autoescape

Alternatively, to totally turn autoescaping off from your Python code, use the autoescape argument when initialising a Context:

c = Context({
   'foo': 'bar',
   'url': 'http://127.0.0.1/test?a=1&b=2',
}, autoescape=False)

如何转动[自动HTML如果您愿意,请参阅文档中的某些内容模板选项。

The How to turn [Automatic HTML escaping] off section of the documentation covers some of the in-template options if you'd rather do it there.

这篇关于如何在django中使用上下文时禁用HTML编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆