【问题标题】:Jinja2 templates rendering with blanks instead of variablesJinja2 模板用空白而不是变量渲染
【发布时间】: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


    【解决方案1】:

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

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

    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 模板使用关键字访问参数(应该如此)。如果您只是将字典传递给渲染函数,则您没有提供此类关键字。

    【讨论】:

    • 就是这样。更改模板似乎更干净,所以我就那样做了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-03-01
    • 2018-08-19
    • 2021-06-06
    • 2014-12-23
    • 1970-01-01
    • 2018-07-29
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多