【发布时间】:2015-11-08 04:26:34
【问题描述】:
我正在使用 jinja2 为我正在构建的框架的“应用程序生成器”生成基本的 Python 代码。
当渲染并写入文件时,jinja2 的输出包含变量应该存在的空白。
我正在从 YAML 配置文件构建一个值的字典
app.pytemplate:
__author__ = {{authorname}}
from plugins.apps.iappplugin import IAppPlugin
class {{appname}}(IAppPlugin):
pass
YAML:
#basic configuration
appname: newApp
version: 0.1
repo_url: ''
#author configuration
authorname: 'Foo Bar'
authoremail: ''
生成代码(我在这里剪掉了一些愚蠢的样板 arg 解析)
# read in the YAML, if present.
with open(yamlPath) as _:
configDict = yaml.load(_)
# Make a folder whose name is the app.
appBasePath = path.join(args.output, configDict['appname'])
os.mkdir(appBasePath)
# render the templated app files
env = Environment(loader=FileSystemLoader(templatePath))
for file in os.listdir(templatePath):
#render it
template = env.get_template(file)
retval = template.render(config=configDict)
if file.endswith(".pytemplate"):
if file == "app.pytemplate":
# if the template is the base app, name the new file the name of the new app
outfile = configDict['appname'] + ".py"
else:
#otherwise name it the same as its template with the right extension
outfile = path.splitext(file)[0] + ".py"
with open(path.join(appBasePath,outfile),"w") as _:
_.write(retval)
YAML 被正确解析(outfile 被正确设置),但输出是:
__author__ =
from plugins.apps.iappplugin import IAppPlugin
class (IAppPlugin):
pass
我做错了什么愚蠢的事情?
【问题讨论】:
标签: python python-3.x yaml jinja2