How do I render jinja2 output to a file in Python instead of a Browser

PythonDjangoJinja2

Python Problem Overview


I have a jinja2 template (.html file) that I want to render (replace the tokens with values from my py file). Instead of sending the rendered result to a browser, however, I want to write it to a new .html file. I would imagine the solution would also be similar for a django template.

How can I do this?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

You can dump a template stream to file as follows:

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

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

Solution 3 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBill G.View Question on Stackoverflow
Solution 1 - PythonsberryView Answer on Stackoverflow
Solution 2 - PythonLim H.View Answer on Stackoverflow
Solution 3 - PythonaychedeeView Answer on Stackoverflow