【问题标题】:How to convert multiple newlines in mako template to one newline?如何将 mako 模板中的多个换行符转换为一个换行符?
【发布时间】:2014-04-28 18:42:30
【问题描述】:

我正在使用 mako templatepython 并尝试使用来自 python 脚本的列表生成文本文件。下面显示了导致问题的部分代码。

% for COMPNAME in tpdob.scalar_modi:
    ${COMPNAME[0]} ${COMPNAME[1]} ${COMPNAME[2]} ${COMPNAME[3]}
% endfor

我正在使用这段代码,但输出很糟糕。
在这里,我在scalar_modi 中有很多列表,并且我将它们一一打印(每个列表有 4 个值)。但问题是,有太多的换行符被打印出来,使得输出的文本文件看起来很难看。 我在网上搜索,但找不到所需的解决方案。 你能帮我解决这个问题吗?

对输出的评论:

使用 ${COMPNAME[0]} ${COMPNAME[1]} ${COMPNAME[2]} ${COMPNAME[3]} ,我得到:
1 42 gzb dli

14 23 tpty sre

32 55 纯正


使用${COMPNAME[0]} ${COMPNAME[1]} ${COMPNAME[2]} ${COMPNAME[3]} \ 时,给出: 11 42 gzb dli14 23 tpty sre32 55 puri ald


我希望它像:
11 42 gzb dli
14 23 tpty sre
32 55 纯正


当使用 if-else 条件时,我得到的甚至超过 2 个 newlines。谁能帮我解决这个问题。我也无法在其文档中找到解决方案:(

【问题讨论】:

    标签: python mako


    【解决方案1】:

    我遇到了同样的问题,看起来像是 Mako Templates for Windows 中的一个错误。提供模板作为字符串而不是文件引用(如下所示)解决了这个问题。

    with open('code.template') as f:
        templateStr = f.read()
    template = mako.template.Template(templateStr)
    

    【讨论】:

    【解决方案2】:

    老话题,但我刚刚发现了使用预处理器 kwarg 的更好方法:

    tpl_lookup = TemplateLookup(directories=['./templates'], output_encoding='utf-8', module_directory='./tmp', preprocessor=[lambda x: x.replace("\r\n", "\n")])
    

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 2010-10-16
      • 2012-01-14
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2021-06-14
      相关资源
      最近更新 更多