Jinja2 模板用空白而不是变量渲染

Jinja2 templates rendering with blanks instead of variables

我正在使用 jinja2 为我正在构建的框架的 "app generator" 生成基本 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 

我做错了什么蠢事?

yaml 模块returns 字典。有两种方法可以解决这个问题:

要么保留模板,但改变将字典传递给渲染方法的方式:

from jinja2 import Template

tmplt = Template('''
__author__ = {{authorname}}
class {{appname}}(IAppPlugin):
''')

yaml_dict = {'authorname': 'The Author',
             'appname': 'TheApp'}

print(tmplt.render(**yaml_dict))

或者您按原样传递字典以呈现和更改模板:

tmplt = Template('''
__author__ = {{yaml['authorname']}}
class {{yaml['appname']}}(IAppPlugin):
''')

yaml_dict = {'authorname': 'The Author',
             'appname': 'TheApp'}

print(tmplt.render(yaml=yaml_dict))

您的 jinja2 模板使用关键字访问参数(应该如此)。如果你只是将字典传递给渲染函数,你就没有提供这样的关键字。