Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 686
Bill G. Avatar asked Aug 08 '12 04:08

Bill G.


People also ask

What is the difference between Jinja and Jinja2?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.


1 Answers

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 
like image 86
sberry Avatar answered Oct 11 '22 21:10

sberry