Strip html comments middleware

 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. GeoDjango maps in admin TabularInlines by alanB 2 years, 7 months ago
  2. "Zoom in" on rendered HTML that the test client returns by peterbe 4 years ago
  3. Effective content caching for mass-load site using redirect feature by nnseva 1 year, 10 months ago
  4. Request time logging middleware by mpasternacki 3 years, 5 months ago
  5. Strip Google Analytics cookies for caching middleware purposes by nf 3 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

#

(Forgotten your password?)