Django stupid mark_safe?
Posted
by Mark
on Stack Overflow
See other posts from Stack Overflow
or by Mark
Published on 2010-04-08T02:24:10Z
Indexed on
2010/04/08
2:33 UTC
Read the original article
Hit count: 362
I wrote this little function for writing out HTML tags:
def html_tag(tag, content=None, close=True, attrs={}):
lst = ['<',tag]
for key, val in attrs.iteritems():
lst.append(' %s="%s"' % (key, escape_html(val)))
if close:
if content is None: lst.append(' />')
else: lst.extend(['>', content, '</', tag, '>'])
else:
lst.append('>')
return mark_safe(''.join(lst))
Which worked great, but then I read this article on efficient string concatenation (I know it doesn't really matter for this, but I wanted consistency) and decided to update my script:
def html_tag(tag, body=None, close=True, attrs={}):
s = StringIO()
s.write('<%s'%tag)
for key, val in attrs.iteritems():
s.write(' %s="%s"' % (key, escape_html(val)))
if close:
if body is None: s.write(' />')
else: s.write('>%s</%s>' % (body, tag))
else:
s.write('>')
return mark_safe(s.getvalue())
But now my HTML get escaped when I try to render it from my template. Everything else is exactly the same. It works properly if I replace the last line with return mark_safe(unicode(s.getvalue()))
. I checked the return type of s.getvalue()
. It should be a str
, just like the first function, so why is this failing??
Also fails with SafeString(s.getvalue())
but succeeds with SafeUnicode(s.getvalue())
.
I'd also like to point out that I used return mark_safe(s.getvalue())
in a different function with no odd behavior.
© Stack Overflow or respective owner