Login

Strip html comments middleware

Author:
trbs
Posted:
March 21, 2007
Language:
Python
Version:
Pre .96
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 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.