Search code examples
pythonhtmlpylonsmako

Strip whitespace from Mako template output (Pylons)


I'm using Mako + Pylons and I've noticed a horrendous amount of whitespace in my HTML output.

How would I go about getting rid of it? Reddit manage to do it.


Solution

  • I'm not sure if there's a way to do it within Mako itself but you can always just do some post-rendering processing before you serve up the page. For example, say you have the following code that generates your horrendous whitespace:

    from mako import TemplateLookup
    
    template_lookup = TemplateLookup(directories=['.'])
    template = template_lookup.get_template("index.mako")
    whitespace_mess = template.render(somevar="no whitespace here")
    return whitespace_mess # Why stop here?
    

    You could add in an extra step like so:

    from mako import TemplateLookup
    
    template_lookup = TemplateLookup(directories=['.'])
    template = template_lookup.get_template("index.mako")
    whitespace_mess = template.render(somevar="no whitespace here")
    cleaned_up_output = cleanup_whitespace(whitespace_mess)
    return cleaned_up_output
    

    ...where cleanup_whitespace() is some function that does what you want (it could pass it through HTML Tidy or slimmer or whatever). It isn't the most efficient way to do it but it makes for a quick example :)