Python 如何从Jinja模板调用方法?

Python 如何从Jinja模板调用方法?,python,template-engine,jinja2,Python,Template Engine,Jinja2,我在一个路径中有几个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(i

我在一个路径中有几个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模板文件名

我已经解决了

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

例如
template.module.foo()
调用jinja模板中的
foo