I'm using Django 1.3 and I have a simple_tag that I need to return some un-escaped HTML and no matter what I do it's still escaping my & to & and my | to %7C.
from django import template
from django.template import loader, Context
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag()
def show_stuff(arg1=None, arg2=None, arg3='someconstant'):
# Do some stuff
if someconstant == 'somevalue':
template_name = 'template1.html'
else:
template_name = 'template2.html'
template = loader.get_template(template_name)
html = template.render(Context( {'myvar': myvar,} ))
html = mark_safe(html)
print type(html)
return html
The print statement reveals
<class 'django.utils.safestring.SafeUnicode'>
which from my understanding isn't supposed to be escaped. I'm calling the tag in my template like so:
{% show_stuff 'arg1' 'arg2' 'arg3' %}
Help would be greatly appreciated.
Update: Tried the following from comments below. Didn't return an error, but still escapes the HTML:
...
template = loader.get_template(template_name)
html = template.render(Context( {'myvar': myvar,} ))
html = mark_safe(html)
print type(html)
return html
show_stuff().is_safe=True
Also tried wrapping the contents of template1.html and template2.html in
{% autoescape off %}
template html contents with & and |
{% endautoescape %}
and wrapping the templatetag call itself with autoescape tags. No success.
Old thread but I ran into the same issue recently. I got it working python 3.6. Assign the value from simple tag to a variable txt and output the txt using template tags "{{" and add safe filter to txt.
{% get_contentvalue user "htmlabout" as txt %}
{{txt|safe}}
In discussion with the author of the question we found that the characters were not actually escaped. Scoopseven (the author) viewed the source html with the option "Show Selection Source" of a context menu in Firefox. In this case escaped characters are shown.
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