Differences between revisions 2 and 3
Revision 2 as of 2005-05-01 07:52:36
Size: 638
Editor: aaron
Comment:
Revision 3 as of 2005-05-01 07:54:09
Size: 679
Editor: aaron
Comment:
Deletions are marked like this. Additions are marked like this.
Line 12: Line 12:
However, it doesn't escape entities beyond {{{&}}}, {{{<}}}, and {{{>}}}. However, it doesn't escape characters beyond {{{&}}}, {{{<}}}, and {{{>}}}.
Line 25: Line 25:
def html_escape( text ): def html_escape(text):
    """Produce entities within text."""

Escaping HTML

The cgi module that comes with Python has an escape function:

   1 import cgi
   2 
   3 s = cgi.escape( """& < >""" )   # s = "&amp; &lt; &gt;"

However, it doesn't escape characters beyond &, <, and >.

Here's a small snippet that will let you escape those as well:

   1 html_escape_table = {
   2     "&": "&amp;",
   3     '"': "&quot;",
   4     "'": "&apos;",
   5     ">": "&gt;",
   6     "<": "&lt;" }
   7 
   8 def html_escape(text):
   9     """Produce entities within text."""
  10     l=[]
  11     for c in text:
  12         l.append( html_escape_table.get(c,c) )
  13     return "".join(l)

Discussion

  • (none yet)

EscapingHtml (last edited 2016-11-19 12:13:41 by OleskandrGavenko)

Unable to edit the page? See the FrontPage for instructions.