today I’d like to show how to render an HTML (or any random non-binary) File with Jinja2 and Python 3.6.
A possible usage for rendering an HTML file is the avoidance of writing duplicate code. I prepared a small HTML file which only consists of a headline and the variable.
As you can see between the h1 tags the text is padded in double curly braces which is the syntax to render variables with Jinja2.
Clearing all conditions
At first, we’re going to install Jinja2 which is needed for Rendering.
Now we’re heading to a new file which will be named renderer.py and start with our imports.
After importing all needed modules we’re going to set up some variables.
- template_filename is the variable which contains the name of the reusable source file.
- rendered_filename is the variable which contains the name of the output file which has been rendered trough Jinja2
- render_vars contains the dictionary which will be passed to Jinja2 to render the source
- script_path contains the absolute path of the renderer.py script. E.g.
- If the absolute path to renderer.py is /home/dummy/renderer.py then it would contain /home/dummy
- template_file_path contains the absolute path to the source template file which will be passed to Jinja2
- rendered_file_path contains the absolute path to the rendered file
Render the source template
Now we’re defining an environment which describes where to find the source template.
We’re using the jinja2.FileSystemLoader() as loader which takes the absolute path to the folder where the template is located.
To render the file and save the output into a variable we execute the render() method on render_environment and pass the render_vars dictionary.
Putting it all together results in a static render script which prints out the rendered text.
Writing the output into an HTML file
To write the output into an HTML File you need to replace the last print line with the With-Statement and write the output_text into rendered_file_path.
As soon as the With-Statement reaches its end, it automatically closes the file and destroys the result_file object. The end of the With-Statement is after the last indented line.
Jinja2 Documentation: http://jinja.pocoo.org/docs/