从Mako模板输出(Pylons)剥离空白

时间:2010-10-06 00:24:09

标签: python html pylons mako

我正在使用Mako + Pylons,我注意到HTML输出中有大量的空白。

我该如何摆脱它? Reddit设法做到了。

5 个答案:

答案 0 :(得分:8)

有反斜杠的事。

以mako http://makotemplates.org的主页为例。

<%def name="makerow(row)">
    <tr>
    % for name in row:
        <td>${name}</td>\
    % endfor
    </tr>
</%def>

但严重的是,我不会花太多时间尝试正确格式化输出。重要的是拥有可读的模板代码。我使用Webkit(或FireBug,如果您愿意)的Web检查器比“查看源代码”更频繁。

如果你真的想要好的格式化html输出,你总是可以写一个中间件来做到这一点。

答案 1 :(得分:4)

没有后处理的唯一方法是避免模板中的空格。但是,这将使您作为开发人员变得非常困难。

您需要决定在渲染模板后清理HTML字符串的时间是否会节省足够的带宽来抵消此成本。我建议使用优化的C代码库为您执行此操作,例如lxml.html

>>> from lxml import html
>>> page = html.fromstring("""<html>
... 
... <body>yuck, a newline! bandwidth wasted!</body>
... </html>""")
>>> html.tostring(page)
'<html><body>yuck, a newline! bandwidth wasted!</body></html>'

答案 2 :(得分:2)

我不确定是否有办法在Mako本身内完成,但在提供页面之前,您总是可以进行一些后期渲染处理。例如,假设您有以下代码生成可怕的空格:

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?

你可以添加一个额外的步骤:

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

...其中cleanup_whitespace()是一些能够完成你想要的功能(它可以通过HTML Tidyslimmer或其他任何方式传递)。它不是最有效的方法,但它提供了一个简单的例子:)

答案 3 :(得分:1)

如果您的数据不是太动态,您可以存储模板输出的优化缓存并将其提供给Web客户端。

答案 4 :(得分:0)

与Dan的答案类似,我通过此函数传递渲染输出,该函数仅保留“故意”空白。我将其定义为连续两次(即空行)

所以

Hello 
There

成为

Hello There

但是

Hello

There

变为

Hello
There

这是代码

def filter_newline(input):
    rendered_output = []
    for line in input.split("\n"):
        if line:
            # Single new-lines are removed
            rendered_output.append(line)
        else:
            # Subsequent newlines (so no body to the interveaning line) are retained
            rendered_output.append("\n")

    return "".join( rendered_output )

执行如此(我偷走了Dan的一部分)

whitespace_mess = template.render(somevar="Hello \nThere")
cleaned_up_output = filter_newline(whitespace_mess)
相关问题