How to output jinja2 to a file in Python instead of browser

I have a jinja2 template (.html file) that I want to display (replace the markers with the values ​​from my py file). However, instead of sending the result to the browser, I want to write it to a new .html file. I would suggest that the solution would also be similar to the django template.

How can i do this?

+60
python django jinja2
Aug 08 2018-12-12T00:
source share
4 answers

How about 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> 

exit

 <h1>Hello World!</h1> 

If you use a framework such as Flask, you can do this at the bottom of the window before returning.

 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 
+98
Aug 08 2018-12-12T00:
source share

You can dump the template stream to a file as follows:

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

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

+29
Jun 29 '16 at 15:59
source share

So, after you have loaded the template, you call the render and then write the output to a file. The 'with' statement is a context manager. Inside the indent, you have an open file that looks like an object named "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) 
+6
Aug 08 2018-12-12T00:
source share

The answers above are from working with amber and achheads, I needed to add f.close (). Otherwise, you may not find your file in your directory.

0
Dec 08 '17 at 14:57
source share



All Articles