【问题标题】:How to call a method from Jinja template?如何从 Jinja 模板调用方法?
【发布时间】:2012-07-22 11:20:37
【问题描述】:

我在一个路径中有几个jinja模板文件,我想渲染它们并将它们写入一个文件,我的问题是它们的输出文件名,

是否可以在 jinja 模板中定义一个函数来返回和准备模板输出文件名,并从 python 代码中调用它并检索它的值?

这是我的代码:

#in here inputPath is jinja templates path
for root, dirs, files in os.walk(inputPath):
    for file in files:
        fPath = root[len(inputPath) + 1:]
        newPath = (fPath + "/" if fPath else '') + file
        template = env.get_template(newPath)
        oPath = os.path.join(outputPath, fPath)
        try:
            os.makedirs(oPath)
        except:
            pass
        oPath=os.path.join(oPath,file)
        with codecs.open(oPath,'w', "utf-8") as f:
            f.write(template.render(projectname=projectName, mainxmlpath=mainXamlPath))

在这段代码中输出的文件名就是jinja模板文件名。

【问题讨论】:

    标签: python template-engine jinja2


    【解决方案1】:

    我已经解决了,

    模板类具有包含所有模板方法和定义变量的模块属性

    例如 template.module.foo() 在 jinja 模板中调用您的 foo 宏。

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 2011-05-15
      • 2014-09-21
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多