[pylons-discuss] Minimize output buffer - How strip Comments

5 views
Skip to first unread message

Mario Moura

unread,
May 18, 2010, 4:48:24 PM5/18/10
to pylons-...@googlegroups.com
Hi Folks

First I tried work with buffers like

------ in my template
  <% 
    mybuffer = context._buffer_stack[0].getvalue()
    ## Here some custom def
    ## Now empty the buffer
    context._buffer_stack[0].data[:] = []
  %>
 
  ${mybuffer}
-------------------
But because of some <%inherit file="/base/index.html"/>\ can turn this approach difficult.

Now I am reading about Middleware and seem be the solution.

I found this Middleware :

StripHtmlCommentsMiddleware

http://djangosnippets.org/snippets/123/

So I did:

./config/middleware.py
from MyApps.lib.middleware import StripHtmlCommentsMiddleware
....
 app = StripHtmlCommentsMiddleware(app)

./lib/middleware.py
this snippet code (http://djangosnippets.org/snippets/123/)

So this snippet code is wrong? Some tip to fix it, (just for test)

There is another Middleware to do this? I dont want reinvent the wheel

Regards


Mario
macm

--
You received this message because you are subscribed to the Google Groups "pylons-discuss" group.
To post to this group, send email to pylons-...@googlegroups.com.
To unsubscribe from this group, send email to pylons-discus...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pylons-discuss?hl=en.

Walter Cruz

unread,
May 18, 2010, 5:01:37 PM5/18/10
to pylons-...@googlegroups.com
    def process_response(self, request, response):
if ("text" in response['Content-Type']):


This will strip the html comments only if the content-type of your page is text..

--
[]'
- Walter
http://waltercruz.com/
http://parabolashoje.com/

Eryx Lee

unread,
May 18, 2010, 6:32:21 PM5/18/10
to pylons-...@googlegroups.com
class StripHtmlCommentsMiddleware:
    """
    Strips all html comments from response content.
    """
    def __init__(self, app):
        self.app = app
        self.htmlcomments = re.compile('\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>')

    def __call__(self, environ, start_response):
        req = Request(environ)
        rsp = req.get_response(self.app)
        if "text/html" == rsp.content_type:
            new_content = self.htmlcomments.sub('', rsp.unicode_body)
            rsp.unicode_body = new_content
        return rsp(environ, start_response)

Mario Moura

unread,
May 19, 2010, 7:06:21 AM5/19/10
to pylons-...@googlegroups.com
Hi Eryx Lee

Works like a charm

Thanks a lot.

Regards

Mario Moura
macm

2010/5/18 Eryx Lee <eryx.l...@gmail.com>
Reply all
Reply to author
Forward
0 new messages