Jinja2模板用空格代替变量呈现

2024-05-14 19:36:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用jinja2为我正在构建的框架生成一个“appgenerator”的基本python代码。在

当呈现并写入文件时,jinja2的输出包含变量应该位于的空白处。在

我正在从YAML配置文件构建一个值dict

在app.pytemplate应用程序公司名称:

__author__ = {{authorname}}
from plugins.apps.iappplugin import IAppPlugin

class {{appname}}(IAppPlugin):
    pass

山药:

^{pr2}$

生成代码(我在这里截取了一些愚蠢的参数解析样板)

# 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 

我做错了什么蠢事?在


Tags: thenameappyamlifaswithtemplate
1条回答
网友
1楼 · 发布于 2024-05-14 19:36:08

yaml模块返回一个字典。有两种解决方法:

或者保留模板,但更改将字典传递给呈现方法的方式:

from jinja2 import Template

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

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

print(tmplt.render(**yaml_dict))

或者按原样传递词典以渲染和更改模板:

^{pr2}$

jinja2模板使用关键字访问参数(应该是这样)。如果只将字典传递给呈现函数,则不提供此类关键字。在

相关问题 更多 >

    热门问题