How to disable HTML encoding when using Context in django

无人久伴 提交于 2019-12-04 09:05:04

问题


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)

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

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.

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


回答1:


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)

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)

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.




回答2:


Or just use the "safe" filter in your template.

Also, I cannot stress enough how important it is to be familiar with Django's documentation; many common questions like this have easy-to-find answers and explanations (like this one), and reading through the docs and getting a feel for how everything works will drastically decrease the amount of time you need to spend ask "why did it do that" and increase the amount of time you spend building things that work the way you want.



来源:https://stackoverflow.com/questions/237235/how-to-disable-html-encoding-when-using-context-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!