如何使用Python而不是浏览器将jinja2输出渲染为文件

时间:2012-08-08 04:06:42

标签: python django jinja2

我有一个我要渲染的jinja2模板(.html文件)(用我的py文件中的值替换标记)。但是,我想将其写入新的.html文件,而不是将渲染结果发送到浏览器。我认为django模板的解决方案也类似。

我该怎么做?

3 个答案:

答案 0 :(得分:101)

这样的事情怎么样?

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", "w") 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

答案 1 :(得分:31)

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

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

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

答案 2 :(得分:7)

因此,在加载模板后,调用render,然后将输出写入文件。 'with'语句是一个上下文管理器。在缩进中,你有一个像对象'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)