Login

Strip html comments middleware

Author:
trbs
Posted:
March 21, 2007
Language:
Python
Version:
Pre .96
Tags:
middleware comments
Score:
3 (after 3 ratings)

Middleware for stripping all html comments from the response content before returning it to the client.

This will also strip inline javascript with htmlcomments put around it!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import re
class StripHtmlCommentsMiddleware:
    """
    Strips all html comments from response content.
    """
    def __init__(self):
        self.htmlcomments = re.compile('\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>')

    def process_response(self, request, response):
        if ("text" in response['Content-Type']):
            new_content = self.htmlcomments.sub('', response.content)
            response.content = new_content
            return response
        else:
            return response

More like this

  1. Strip trailing .html extensions from URLs so that existing bookmarks work for a legacy site ported to Django by daverowell 8 years, 3 months ago
  2. Template tag for stripping blank lines by akaihola 7 years, 7 months ago
  3. Cheetah-style comments by olivier 8 years, 1 month ago
  4. Updated version of StripWhitespaceMiddleware (v1.1) by sleepycal 4 years, 3 months ago
  5. HTML Validation Middleware by adamcik 6 years, 6 months ago

Comments

pedromagnus (on May 13, 2011):

Hi, nice code! Something to note: in case you want some comment to pass through (like the conditionals for IE to load extra css), you can make it adding an extra '-' in the comment tag like this:

    <!---[if IE 7]>
        ...
    <![endif]--->

Cheers, Pedro

#

Please login first before commenting.