如何用 Python 而不是 Browser 将 jinja2输出呈现到文件中

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

我怎么能这么做?

97109 次浏览

How about something like this?

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>

output

<h1>Hello World!</h1>

If you are using a framework, such as Flask, then you could do this at the bottom of your view, before you return.

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

So after you've loaded the template, you call render and then write the output to a file. The 'with' statement is a context manager. Inside the indentation you have an open file like object called '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)

You can dump a template stream to file as follows:

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

Ref: https://jinja.palletsprojects.com/en/2.9.x/api/#jinja2.environment.TemplateStream.dump