jinja2Getting started with jinja2


Remarks

Jinja 2 is a templating engine for Python, which means that it allows developer to produce web pages, containing for example base html code and placeholders for Jinja 2 to fill them. Based upon Django's templating system, Jinja is one of the most used as it allows developers to use powerful concepts like sandboxing and inheritance to allow a template easily reused.

Jinja is simple. You have a template with a bunch of holes in it. You then ask the engine to fill the template with the values you give it at runtime, and ther response is handed back to you, in form of an html document, ready to be sent to the user. You also have more advanced possibilities like applying a filter on a variable, to show for example a read time based on an article page for a blog, or simply pluralize words like a breeze.

You can read more on Jinja2 through the official documentation here

Jinja2 installation and setup

Install the dependencies:

pip install jinja2

Install a framework:

pip install flask

Create the following structure

├── run.py
└── templates
 

Put a file template.html in the templates directory. The file can contain a jinja 2 variable named my_string .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{my_string}}
</body>
</html>
 

Open the file run.py and put in the following contents.

from flask import Flask, render_template
app = Flask(__name__)


@app.route("/")
def template_test():
    return render_template('template.html', my_string="Wheeeee!", my_list=[0,1,2,3,4,5])


if __name__ == '__main__':
    app.run(debug=True)
 

Now you can run your webapp using python run.py and the output will appear with your local host http://localhost:5000