Jinja is a library used with Python. Jinja can be used in:
- A Python script
- A Flask App
- Ansible (because Ansible uses Python)
To use Jinja in a Python script, you will first need to install Python on your system. Often, pip is used to install Jinja. The pip list and pip show commands can be used to determine if Jinja is installed.
~]$ pip list
Package Version
---------------------------------- ------------------
Jinja2 2.11.2
If Jinja is not installed, the pip install command can be used to install Jinja.
pip3 install Jinja2
And here is an example of how to create a Jinja variable ("name" in this example) and then use the Jinja templating system to print the value ("John Doe" in this example) in a Python script.
#!/usr/bin/python
from jinja2 import Template
name = "John Doe"
template = Template("Hello {{ name }}")
message = template.render(name=name)
print(message)
Here is an example of how to use Jinja in a Flask app in VSCode. Check out my article Getting Started with Flask using VSCode on Windows.
Let's say your Flask app has the following files and directories.
├── main.py
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── templates (directory)
│ │ ├── home.html
And main.py has the following.
from my-project import app
app = app()
if __name__ == '__main__':
app.run()
Add __init__.py has the following.
from flask import Flask
def app():
app = Flask(__name__)
from .views import views
app.register_blueprint(views, url_prefix='/')
return app
Add views.py has the following.
from flask import Blueprint, render_template
views = Blueprint('views', __name__)
@views.route('/')
def home():
return render_template('home.html')
And home.html has the following. In this example, the jinja lower filter is used to change Hello World to lower.
{{ 'Hello World' | lower }}
Did you find this article helpful?
If so, consider buying me a coffee over at