Create Jinja templates in Python Script

Reading Time: 2 minutes

Hi readers, In this blog, we will be looking at creating Jinja templates and passing variables in them using python script also how to use them for creating dynamic pages.

Jinja as templating engine

Jinja2 is a full-featured template engine for Python. Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the evaluation of templates is in a sandbox.

Delimiters

Jinja uses various delimiters in the template strings.

{%....%}  block for statements

{{....}}  expressions used to print to template output

{#....#} block expressions comments that are not included in the template output

#....## block used as line statements

let create a simple e-mail template in jinja having list of inventory with sender and reciver.

email.j2

Hello {{ receiver }}
{{ "list of inventory is given below" }}
  {%- for item in item_list %}
    {{ item }}
  {%- endfor %}
Thank you
{{ sender }}

let write python script for our jinja file such as passing sender ,receiver name and list of inventory.

jinja.py

#!/usr/bin/env python
from jinja2 import Template
import optparse

parser = optparse.OptionParser()
parser.add_option('-s', '--sender', dest='sender', help='sender name')

parser.add_option('-r', '--receiver', dest='receiver', help='receiver name')

(options, args) = parser.parse_args()
if options.sender is None:
    options.sender = raw_input('Enter sender Name:')

if options.receiver is None:
    options.receiver = raw_input('Enter receiver Name :')

with open('email.j2') as f:
    tmpl = Template(f.read())
print tmpl.render(sender = options.sender,receiver=options.receiver,item_list = ["scala", "jinja", "akkka", "java", "ansible", "jenkins"])

The above example asks for a sender name, receiver name and take list of inventory then generates a message string, which is printed to the user. The template engine is similar to the Python format() method; but template engines are more powerful and have many more features.

from jinja2 import Template

We import the Template object from the jinja2 module. Template is the central template object. Template represents a compiled template and iused to evaluate .

parser.add_option('-s', '--sender', dest='sender', help='sender name')

Adding an option for the sender for passing in argument similarly for the receiver.

if options.sender is None:

Check for the option whether the value is passed as an argument if not then ask from the command line.

with open('email.j2') as f:

Opening jinja file if present in the same directory then pass basename only else pass the reference path.

tmpl = Template(f.read())

Reading template from jijna file(email.j2).

print tmpl.render(sender = options.sender,receiver=options.receiver,item_list = ["scala", "jinja", "akkka", "java", "ansible", "jenkins"])

passing variable into jinja file and print them into screen.

conclusion

Jinja is a web template engine for the Python programming language. Template engines take in tokenized strings and produce rendered strings with values in place of the tokens as output. Templates are typically used as an intermediate format written by developers to programmatically produce one or more desired output formats, commonly HTML, XML or PDF.

Written by 

I always love to learn and explore new technologies. Having working skills in Linux, AWS, DevOps tools Jenkins, Git, Maven, CI-CD, Ansible, Scripting language (shell/bash), Docker as well as ELK stack and Grafana for implementing logging and visualization technology.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading