如何将jinja2输出呈现给Python中的文件而不是浏览器

我有一个jinja2模板(.html文件),我想渲染(用我的py文件中的值replace标记)。 但是,我不想将渲染结果发送到浏览器,而是将其写入一个新的.html文件。 我会想象解决scheme也将类似的Django模板。

我怎样才能做到这一点?

这样的事情呢?

from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates')) template = env.get_template('test.html') output_from_parsed_template = template.render(foo='Hello World!') print output_from_parsed_template # to save the results with open("my_new_file.html", "wb") as fh: fh.write(output_from_parsed_template) 

的test.html

 <h1>{{ foo }}</h1> 

产量

 <h1>Hello World!</h1> 

如果你正在使用一个框架,比如Flask,那么你可以在你的视图的底部做这个,在你返回之前。

 output_from_parsed_template = render_template('test.html', foo="Hello World!") with open("some_new_file.html", "wb") as f: f.write(output_from_parsed_template) return output_from_parsed_template 

您可以将模板stream转储为文件,如下所示:

 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') 

参考: http : //jinja.pocoo.org/docs/dev/api/#jinja2.environment.TemplateStream.dump

所以在你加载模板之后,你调用了render,然后把输出写到一个文件中。 'with'语句是一个上下文pipe理器。 在缩进内部,你有一个打开的文件,比如叫做“f”的对象。

 template = jinja_environment.get_template('CommentCreate.html') output = template.render(template_values)) with open('my_new_html_file.html', 'w') as f: f.write(output)