Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用空格而不是变量呈现Jinja2模板_Python_Python 3.x_Yaml_Jinja2 - Fatal编程技术网

Python 使用空格而不是变量呈现Jinja2模板

Python 使用空格而不是变量呈现Jinja2模板,python,python-3.x,yaml,jinja2,Python,Python 3.x,Yaml,Jinja2,我正在使用jinja2为我正在构建的框架的“应用生成器”生成基本python代码 当呈现并写入文件时,jinja2的输出包含变量应该出现的空格 我正在从YAML配置文件构建一个dict值 app.pytemplate: __author__ = {{authorname}} from plugins.apps.iappplugin import IAppPlugin class {{appname}}(IAppPlugin): pass tmplt = Template(''' __

我正在使用jinja2为我正在构建的框架的“应用生成器”生成基本python代码

当呈现并写入文件时,jinja2的输出包含变量应该出现的空格

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

app.pytemplate:

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

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

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

print(tmplt.render(yaml=yaml_dict))
亚马尔:

#basic configuration
appname:  newApp
version:  0.1
repo_url: ''
#author configuration
authorname: 'Foo Bar'
authoremail: ''
生成代码(我在这里截取了一些愚蠢的样板文件arg解析)

YAML被正确解析(
outfile
被正确设置),但输出是:

__author__ = 
from plugins.apps.iappplugin import IAppPlugin


class (IAppPlugin):
    pass 

我做错了什么蠢事

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

就是这样。更改模板看起来更干净,所以我就这样做了。谢谢