【发布时间】:2012-08-05 03:36:51
【问题描述】:
我有一个要渲染的 jinja2 模板(.html 文件)(用我的 py 文件中的值替换标记)。但是,我不想将渲染结果发送到浏览器,而是将其写入新的 .html 文件。我想对于 django 模板来说,解决方案也是类似的。
我该怎么做?
【问题讨论】:
我有一个要渲染的 jinja2 模板(.html 文件)(用我的 py 文件中的值替换标记)。但是,我不想将渲染结果发送到浏览器,而是将其写入新的 .html 文件。我想对于 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", "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
【讨论】:
rb改成wb。
)。我试图添加它,但 SO 要求编辑大于 6 个字符(愚蠢的限制)..
所以在你加载了模板之后,你调用 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)
【讨论】:
您可以将模板流转储到文件中,如下所示:
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
参考:http://jinja.pocoo.org/docs/dev/api/#jinja2.environment.TemplateStream.dump
【讨论】: