Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().
Closest thing I know about is cgi.escape.
from django.utils.html import escape
print escape('<div class="q">Q & A</div>')
Building on @garlon4 answer, you can define your own htmlspecialchars(s)
:
def htmlspecialchars(text):
return (
text.replace("&", "&").
replace('"', """).
replace("<", "<").
replace(">", ">")
)
You probably want xml.sax.saxutils.escape:
from xml.sax.saxutils import escape
escape(unsafe, {'"':'"'}) # ENT_COMPAT
escape(unsafe, {'"':'"', '\'':'''}) # ENT_QUOTES
escape(unsafe) # ENT_NOQUOTES
Have a look at xml.sax.saxutils.quoteattr, it might be more useful for you
I think the simplest way is just to use replace:
text.replace("&", "&").replace('"', """).replace("<", "<").replace(">", ">")
PHP only escapes those four entities with htmlspecialchars. Note that if you have ENT_QUOTES set in PHP, you need to replace quotes with ' rather than ".
The html.entities
module (htmlentitydefs
for python 2.x) contains a dictionary codepoint2name
which should do what you need.
>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'
Only five characters need to be escaped, so you can use a simple one-line function:
def htmlspecialchars(content):
return content.replace("&", "&").replace('"', """).replace("'", "'").replace("<", "<").replace(">", ">")
If you are using django 1.0 then your template variables will already be encoded and ready for display. You also use the safe
operator {{ var|safe }}
if you don't want it globally turned on.
© 2022 - 2024 — McMap. All rights reserved.