Rendering text from Jinja Template using Python
Rendering a jinja template always results in some text (obviously, since this is what jinja is all about as stated earlier). Rendering a template using a python file involves the following steps –
- Step 1: Import the necessary libraries and components (objects, functions, etc.) from libraries.
- Step 2: Create a jinja rendering environment and store it in a variable. This environment will be used in further steps.
- Step 3: Load the template in a variable.
- Step 4: Render the template using <template-object>.render() function to obtain text.
- Step 5: Print the rendered text to the screen or a file as suitable.
Following is an example to demonstrate the above process.
Printing “Hello World” with Jinja
Create a jinja template named “helloWorld.jinja” and save it in templates folder. Here are the contents of this file –
Hello World!
Create a python file named “helloWorld.py” and save it directly under the jinjaTests folder. This file will render the “helloWorld.jinja” template. Here are the contents of this file.
After importing the necessary components from “jinja2” module we load the environment using the “Environment()” function citing the templates folder as the folder for keeping templates. While loading jinja templates, the environment will search for the templates relative to this folder. Next, we load the template using “<environment-object>.get_template(<path to the template>)” function where the path to the template is relative to the templates folder as stated and store it in variable named “template”. Next we render the template using “<template-object>.render()” function which outputs the rendered text (string). We store the output string in the variable output. Finally, we print the string stored in output on the screen.
Python3
from jinja2 import Environment, FileSystemLoader env = Environment(loader = FileSystemLoader( 'templates' )) template = env.get_template( 'helloWorld.jinja' ) output = template.render() print (output) |
Output
Hello World!
Saving the output of rendering a Jinja template to a file
To save the output to a file, we just need to write the output string to a file instead of the screen in last example. One way to do this is by replacing the print line (last line) with the following code in helloWorld.py –
with open("renders/outputFileName.txt", 'w') as f:
print(output, file = f)
Running the “helloWorld.py” with this code will create a file named “outputFileName.txt” in the renders folder (or any other location you specify).
Getting started with Jinja Template
This article introduces Jinja and then describes the basics of working with it which includes how to render templates using Jinja and Python3, passing data to the template through arguments, and basic Jinja syntax (delimiters, expressions, control structures – decisions and loops). A few examples including creating a simple static HTML page are presented.
Contact Us