Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple and effective blog focusing on Jinja Templating in Python

# Jinja Templating with Python

Jinja : What and Why

Jinja is a web template engine for the Python programming language which is fast, expressive and extensible.Special placeholders in the template allow writing code similar to Python syntax which renders the final document when the data in passed (if needed).

Features

  • Template inheritance
  • Compiles down to the optimal Python code just-in-time
  • Optional ahead-of-time template compilation
  • Easy to debug
  • Extensible filters, tests, functions, and even syntax.

Prerequisites

Jinja works with Python 2.7.x and >= 3.5. If you are using Python 3.2 you can use an older release of Jinja (2.6) as support for Python 3.2 was dropped in Jinja version 2.7. The last release which supported Python 2.6 and 3.3 was Jinja 2.10.

Installation

Install and update using pip

$ pip install -U Jinja2

Templating at First Sight

#import the `Template` object from the `jinja2` module 
from jinja2 import Template

#`Template` is the central template object which is compiled
template = Template("See it's so {{ str }}.")

#`render()` method will generate the final output
print(template.render(str='easy'))

Lets dive down

  • Jinja uses various delimiters in the template strings.

    • {% %} , statements
    • {{ }} , expressions to print to the template output
    • {# #} ,comments which are not included in the template output
  • Jinja can work directly with objects and dictionaries in python by using . operator

     class Emp:
     	def __init__(self, name, id):
     	        self.name = name
     	        self.id = id
     	def getId(self):
     	        return self.id
     	def getName(self):
     	        return self.name    
    
     emp1 = Emp('Sam',1)
    
     template = Template("Hello {{ emp.getName() }} ,you are hired and your id is {{ emp.getId() }}")
     print(template.render(emp=emp1))
     
    

Decision Making in Jinja

Conditionals are expressions that are evaluated when a certain condition is met.

Syntax with example :

{% if season == 'winter' %}
	"Keep AC off"
{% else %}
	"keep AC on"
{% endif %}

Jinja for expression

The for expression is used to iterate over a data collection in a template.

Syntax with example:

{% for season in seasons %}
    {{ season.desiredFood }}
{% endfor %}

Lets see a complete example

from jinja2 import Template ,Environment, FileSystemLoader

# templates folder contains template files
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

def personIntro(person):
	template = env.get_template('template_person_intro.txt')
	print(template.render(person=person))

person1 = { 'name':'Sam' , 'age':10 , 'gender':'male' , 'hobby':'eating' }
person2 = { 'name':'Samira' , 'age':10 , 'gender':'female' , 'hobby':'drinking' }


personIntro(person1)
personIntro(person2)

Below is template_person_intro.txt file which will reside in templates folder.

{# This template introduces a person #}

Introducing {{ person.name }}
{% if person.gender == 'male' %}
	He is {{ person.age}} years old.
	His hobby is {{ person.hobby}}.
{% else %}
	She is {{ person.age}} years old.
	Her hobby is {{ person.hobby}}.
{% endif %}

If everything goes well till the point you will have an output similar to the one provided below.

knoldus@knoldus-Vostro-3546:~/Desktop/python-scripting$ python3 python-jinja.py 

Introducing Sam

	He is 10 years old.
	His hobby is eating.


Introducing Samira

	She is 10 years old.
	Her hobby is drinking.
	
knoldus@knoldus-Vostro-3546:~/Desktop/python-scripting$ 

The above discussed topics will help any beginner to understand and also to do hands-on Jinja Templating using python.

Keeping exploring !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment