In this article we will talk about Jinja the template engine used in the Python ecosystem. Created in 2008 by Armin Ronacher, the same creator of the Flask micro framework. It is used to create dynamic documents by combining static models (templates) with variable data, its applications are found in particular in web applications such as Flask, Bottle, Django and tools such as Ansible and Pellican, but not only that, it can also be used directly on programs in the Python environment. Often also trivially called Jinja2 in reference to its release version, it has the main purpose of dividing the graphic aspect from the logical code, making the program structure cleaner and more maintainable. Jinja is an open source, independent, and always continuously updated project, it appears to be safe, reliable, maintainable, feature-rich and simple to use. the aim is to combine text and graphics models with a business logic that returns data such as variables, lists, dictionaries, objects, Json elements. With Jinja you can create text or markup documents such as Html, Json, Xml, Csv, Txt, Latex, etc…
What is a template
Before proceeding with the examples, it is appropriate to dwell on defining what a template is. A template (shape, mould) is the structure of a document made up of predefined lines of text, located in a specific position, with empty spaces to be filled with variable data. The layout of the document called layout remains unchanged, only the data changes.
In Fig. 1 you can see an example of a template with predefined text parts and variable parts. In the web field, templates are sample documents for the development of other web pages with identical graphics and formatting but with different contents. Now that we have seen what templates are, let’s see what Jinja does. Jinja generates dynamic text blocks in a predefined structure, so everything is based on two major players which are the template and the data. The templates formed by graphics, predefined structures with placeholders located in them that will be replaced by data. And the data that can be simple variables, lists, dictionaries or objects taken from a database, or Json or other types of documents, there can also be data generated dynamically through algorithms.
The visualization of data in a template is called rendering. Jinja as well as managing data rendering also has other features such as:
- Tags containing structured code (control structures and loops) ;
- Template inheritance;
- The use of Macros ;
- A code auto-escaping system;
- A Sandbox to make your code more secure;
- Filters ;
- Tests ;
- A Unicode support.
Installation
Installing Jinja is very simple, just open a shell and use the python pip installer, typing the following code.
pip install jinja2
Obviously the installation of the package should be done in a virtual environment, to keep the projects well separated from each other, avoiding conflicts between various versions.
Examples
Now let’s see how to use Jinja2 through some examples. But first, let’s see how placeholders are defined in the template.
To render simple variables, insert the dynamic data between double curly braces {{}}
<p>The variable {{myVariable}} appears between the braces</p>
To use control structures or loops use the following opening and closing tags {% structure %} {% endstructure %}
{* control structure *}
{% if true %}
print("ok")
{% else %}
print("nok)
{% endif %}
{* cycle for *}
{% for a in range(1,10) %}
print(a)
{% endfor %}
To write comments use {* …comment… *}
Example of basic template.
Let’s see how to create a basic template. After installing the Jinja library, create a folder with a name of your choice, inside it create a file called main.py which will contain the code to create the document rendering engine.
import jinja2
environment = jinja2.Environment()
template = environment.from_string("Hello, {{ name }}!")
print(template.render(name="World"))
Let’s try launching the program from the shell with the command:
python main.py
And we see the word Hello, World! printed on the screen, we have just generated our first document from a partly static and partly dynamic string.
Template example from a file
For this example we will make use of HTML to generate dynamic web pages. Let’s take the newly created project and add a folder called templates and inside it a file called index.html which will be the template from which we will generate the document. Now let’s write some code. Let’s modify the main.py file with the following listing.
from jinja2 import Environment, PackageLoader, select_autoescape, FileSystemLoader
import webview
* Save in a variable the folder where the various 'templates' files reside
* Which can be html, xml, csv, json, latex, txt, ecc......
file_loader = FileSystemLoader('templates')
* I create the environment where jinja2 lives
* All configurations will be managed here
env = Environment(
loader=file_loader, * Loading the path to the template files
autoescape=select_autoescape() * I use auto escape
)
* Retrieving the template using the get_template() method
template = env.get_template("index.html")
* With the render() method I render the template
print(template.render())
* Extra: using the pywebview package I render the HTML I used
* in the example
titleWindow = "My window"
webview.create_window(titoloWindow, html = template.render())
webview.start()
From the previous listing we see that some modules have been imported from the Jinja2 library, including Environment which, once instantiated, will be used to configure the environment where the template will live. Other modules we imported are select_autoescape and FileSystemLoader. select_autoescape is used to enable automatic escaping of Jinja, sometimes when generating HTML documents from templates there is a risk that the rendering of variables will affect the resulting HTML. FileSystemLoader is used to indicate the folder where the templates are located. Note that in the project, in order to view the result in a graphical version, we helped ourselves with the pywebview library which creates desktop applications using html code. To install it, type the following command.
pip install pywebview
Now let’s see the template code, insert the following listing inside index.html.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</body>
</html>
Let’s run the program with the python main.py command and see the final result.
Dynamic template example
In the following example we will insert dynamic data into the template. edit the main.py file as follows.
from jinja2 import Environment, PackageLoader, select_autoescape, FileSystemLoader
import webview
env = Environment(
loader = FileSystemLoader('templates'),
autoescape=select_autoescape()
)
* Retrieving the template using the get_template() method
template = env.get_template("example_passing_variables.html")
* With the render() method I render the template
* Among the arguments of the render method I can pass data to be displayed in the 'templates'
* The data can be of any type variables, lists, dictionaries, objects, json
view = template.render(
title = "Example passing variables",
subtitle = "To render the variables, insert the placeholder between {{}}"")
print(view)
* Extra: via the pywebview package I render the HTML I used
* in the example
windowTitle = "My window"
webview.create_window(windowTitle, html = view)
webview.start()
Now let’s edit the index.html file as follows.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>{{titolo}}</h1>
<h3>{{sottoTitolo}}</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</body>
</html>
Vediamo il risultato finale.
In this tutorial we have seen what the Jinja2 library is, we have also seen how it is used through small examples, in the next tutorials we will enrich our baggage by seeing other features that make this template engine a valid development tool.
SviluppoMania
Stay Tuned