开发者

How can I strip whitespace and newlines with Mako templates? My 12362 line HTML file is killing IE

I'm using the Mako template system in my Pylons website and am having some issues with stripping whitespace.

My reasoning for stripping whitespace is the generated HTML file comes out as 12363 lines of code. This, I assume, is why Internet Explorer is hanging when it tries to load it.

I want to be able开发者_如何学Python to have my HTML file look nice and neat so I can make changes to it with ease and have the generated output look as ugly and messy as required to cut down on filesize and memory usage.

The Mako documentation http://www.makotemplates.org/docs/filtering.html says you can use the trim flag but that doesn't seem to work. Example code:

<div id="content">
    ${next.body() | trim}
</div>

The only way I've been able to strip the newlines is to add a \ (backslash) to the end of each line. This is rather annoying when coding the views and I'd prefer to have a centralized solution.

How do I remove the whitespace/newlines ?


I don't believe IE hanging is due to the file size. You have probably just found a combination of markup that hits an IE bug that causes it to freeze. Try trimming down you document until the freeze no longer happens to isolate the offending piece of markup pattern (and then avoid the markup pattern), or try changing the markup until this no longer happens.

Another good thing to do would be to run your page through HTML validator and fixing any issues reported.


I'm guessing that the trim filter is treating your html as a single string, and only stripping the leading and trailing whitespace characters. You want it to strip whitespace from every line. I would create a filter and iterate over each line.

<%!
    def better_trim(html):
        clean_html = ''
        for line in html:
            clean_html += line.strip()
        return clean_html
%>

<div id="content">
    ${next.body() | better_trim}
</div>


You could create your own simple WSGI Middleware to strip whitespace from your templates after they've been rendered (possibly using the methods described in this answer).

Below is a quick example which might help you get started. Note: I wrote this code without testing or even running it; it may work first time, but it probably won't suit your needs so you'll need to expand on this yourself.

class HTMLMinifyMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        resp_body = self.app(environ, start_response)

        for i, part in enumerate(resp_body):
            resp_body[i] = ' '.join(part.split())

        return resp_body
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜