gpt4 book ai didi

python - 如何从 Jinja 模板调用方法?

转载 作者:行者123 更新时间:2023-12-01 05:58:05 25 4
gpt4 key购买 nike

我的路径中有一些 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.foo() 在 jinja 模板中调用 foo 宏。

关于python - 如何从 Jinja 模板调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11599842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com