0
我正在使用jinja2爲我正在構建的框架生成一個「應用程序生成器」的基本Python代碼。Jinja2模板呈現空白而不是變量
當呈現並寫入文件時,jinja2的輸出包含變量應該是的空格。
__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: ''
生成代碼(我已經剪掉了一些愚蠢的樣板
我從YAML配置文件
app.pytemplate建設值的字典arg parsing here)
# 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
什麼愚蠢的事情我做錯了什麼?
就是這樣。改變模板看起來很乾淨,所以我就這樣走了。謝謝。 – gvoysey