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?
For example, you can check if my_textfield contains a script tag. If so, mark the instance as malicious and return an escaped version of my_textfield (the normal Django behavior). Otherwise, use mark_safe to return your HTML code marked as safe.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Escaping is turning non-safe characters - like HTML tags - into escaped versions so that malicious content such as script tags don't ruin your site. Django does this by default on all content rendered in a template from a variable.
{% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it. Blocks are identified by their name. Usage: {% block content %} <html_code> {% endblock %} .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With