Passing data to the Jinja template
We can pass data to the jinja template from the rendering python program by passing keyword argument(s) to the “<template-object>.render()” function. The keys of these arguments can be used to access the respective values in the expression delimiters (i.e., {{ }}) inside the template. Here is an example to print hello to a name passed to the template by the rendering python program –
Example
Save a template named “helloName.jinja” in the templates folder with the following content –
Hello {{name}}!
Next save the rendering python program named “helloName.py” in the jinjaTests folder with the following content –
Python3
from jinja2 import Environment, FileSystemLoader # loading the environment env = Environment(loader = FileSystemLoader( 'templates' )) # loading the template template = env.get_template( 'helloName.jinja' ) # rendering the template and storing the resultant text in variable output output = template.render(name = 'Geeks' ) # printing the output on screen print (output) |
Running this file produces the following text output on the screen –
Hello Geeks!
Note that we passed the “name” argument to the render function which is accessed in the template inside the expression delimiters. More on delimiters in syntax section.
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.