使用模板引擎生成代码(文本)



我在一个配置文件夹中有一堆yaml文件,模板文件夹中的模板束。我拥有的用例是基于YAML配置和模板生成文本文件。我想看看是否可以使用Python诱人的引擎来解决此问题。

我看到该模板引擎在Web开发环境中使用。我拥有的用例非常相似(但不一样)。我想生成一些文字。它不必在网页上显示。相反,它应该仅生成一个文本文件。

示例 输入: 配置文件夹:config/yaml1,config/yaml2,config/yaml3 .. 模板:template/template1,template/template2,template3。

输出

scripts/script1, script2, script3

脚本的数量=模板数

有两种类型的模板

一个直接/直接替代示例

YAML1:
    Titles:4
    SubTitles:10
Template1:
Number of Titles {Titles} where as Number of Subtitles is {SubTitles}

其他模板是一个嵌套模板。基本上,需要根据yaml示例对模板进行循环:

    YAML2:
        Book: "The Choice of using Choice"
            Author: "Unknown1"
        Book: "Chasing Choices"
            Author:"Known2"
Template2
Here are all the Books with Author Info
The author of the {Book} is {Author}

预期输出是一个具有

的单个文本文件

标题数4,其中字幕数为10选择使用选择的作者是未知的1追逐选择的作者是已知的2

有人可以朝正确的方向发布吗?

您可以使用正则表达式进行此操作,然后搜索/替换。您可以将函数而不是字符串传递到re.sub函数。当然,它依赖于有效的yaml:

yaml1:    标题:4    # ^在这里需要空间    字幕:10模板1:    标题数{titles},其中作为字幕数为{字幕}的数量    #在这里需要缩进

Python代码看起来像这样:

import re
import yaml
# Match either {var}, {{, or }}
TEMPLATE_CODE = re.compile(r'{(w+)}|{{|}}')
def expand(tmpl, namespace):
    print(namespace)
    def repl(m):
        name = m.group(1)
        if name:
            # Matched {var}
            return str(namespace[name])
        # matched {{ or }}
        return m.group(0)[0]
    return TEMPLATE_CODE.sub(repl, tmpl)
def expand_file(path):
    with open(path) as fp:
        data = yaml.safe_load(fp)
    print(expand(data['Template1'], data['YAML1']))

这是输出:

标题数4,其中字幕数为10

当然,有很多使这种更复杂的方法,例如使用适当的模板引擎。

最新更新