Commits

Anonymous committed 5df5c4a

New helper ``strip_tags()`` deletes HTML tags in a string.

Comments (0)

Files changed (2)

     recommended instead).
   - Add OptionGroup class and optgroup support to select().  Patch by
     Alexandre Bourget.
+* webhelpers.html.tools:
+  - New helper ``strip_tags()`` deletes HTML tags in a string.
 * webhelpers.paginate:
   - convert "_range" and "_pagelink" function to Page class method so that they
     can be overridden

webhelpers/html/tools.py

 from webhelpers.html.tags import convert_boolean_attrs
 
 __all__ = [
+    'auto_link', 
     'button_to', 
+    'highlight', 
     'mail_to',
-    'highlight', 
     'strip_links',
-    'auto_link', 
+    'strip_tags',
     ]
 
+tag_re = re.compile(r'<.*?>', re.S)
+br_re = re.compile(r'<br.*?>', re.I|re.S)
+comment_re = re.compile(r'<!--|-->')
 
 AUTO_LINK_RE = re.compile(r"""
                         (                          # leading text
         lit = lambda x: x
     strip_re = re.compile(r'<a\b.*?>(.*?)<\/a>', re.I | re.M)
     return lit(strip_re.sub(r'\1', text))
+
+def strip_tags(text):
+    """Delete any HTML tags in the text, leaving their contents intact.
+    Convert newlines to spaces, and <br /> to newlines.
+
+    Example::
+        >>> strip_tags('Text <em>emphasis</em> <script>Javascript</script>.')
+        'Text emphasis Javascript.'
+        >>> strip_tags('Ordinary <!-- COMMENT! --> text.')
+        'Ordinary  COMMENT!  text.'
+        >>> strip_tags('Line\\n1<br />Line 2')
+        'Line 1\\nLine 2'
+
+    Implementation copied from ``WebOb``.
+    """
+    text = text.replace('\n', ' ')
+    text = text.replace('\r', '')
+    text = br_re.sub('\n', text)
+    text = comment_re.sub('', text)
+    text = tag_re.sub('', text)
+    return text
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.