使用单个模板渲染到自定义输出文件名

时间:2012-12-17 14:59:41

标签: python jinja2

我需要使用与jinja相同的模板创建一系列报告。但我想将每个报告放在不同的渲染文件中。

我在jinja的文档中找不到相关内容。

有没有办法修改渲染的输出文件名?

2 个答案:

答案 0 :(得分:2)

也许这会有所帮助?

import jinja2

env = jinja2.Environment( loader = jinja2.FileSystemLoader('templates/') )

def render_template( filename_template, filename_output ):
  nice = env.get_template( filename_template ).render()
  with open(filename_output,'w') as fh:
    fh.write(nice)

答案 1 :(得分:0)

不同文件有什么问题?

>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> for n in ["John", "Doe"]:
>>>     with open(n + ".txt", "w") as f:
>>>         print >> f, template.render(name=n)