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

Bil*_* G. 70 python django jinja2

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

我怎样才能做到这一点?

sbe*_*rry 107

这样的事怎么样?

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)
Run Code Online (Sandbox Code Playgroud)

的test.html

<h1>{{ foo }}</h1>
Run Code Online (Sandbox Code Playgroud)

产量

<h1>Hello World!</h1>
Run Code Online (Sandbox Code Playgroud)

如果您使用的是框架,例如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
Run Code Online (Sandbox Code Playgroud)


Lim*_* H. 34

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

Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
Run Code Online (Sandbox Code Playgroud)

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


ayc*_*dee 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)
Run Code Online (Sandbox Code Playgroud)