尝试通过嵌套这样的模板来生成代码DRYer:
base = Template('''
- alert:
cluster: {{cluster}}
role: {{role}}
slack: {{slack}}
''')
alert = Template('''
{% include base %}
description: Critical {{role}} system load
threshold: xxx-yyy-zzz
''')
print alert.render(cluster='cluster1', slack='alerts', role='database')
以上不起作用,获得例外:
File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 2, in top-level template code
TypeError: no loader for this environment specified
请告知。
答案 0 :(得分:1)
在呈现base
模板时,您只是没有将引用传递给alert
。
>>> print alert.render(cluster='cluster1', slack='alerts', role='database', base=base)
################ just pass this reference of `base` ^
- alert:
cluster: cluster1
role: database
slack: alerts
description: Critical database system load
threshold: xxx-yyy-zzz