Skip to content

Jinja2 Basics

Jinja2 is a Python-based templating engine. It acts as a bridge between your data (Python variables/dictionaries) and your text files (HTML, Configs, Scripts). Instead of hardcoding values, you use placeholders that Jinja2 fills in dynamically.

  • {{ variable }}: Expressions — Prints the actual value (e.g., {{ user_name }}).
  • {% statement %}: Logic — Handles loops and conditionals (e.g., {% for ... %}).
  • {# comment #}: Hidden Notes — Ignored by the engine; won’t appear in the final file.
  • FileSystemLoader: This is the “Path Finder.” It tells Jinja2 exactly which folder on your hard drive contains your template files (like .html, .j2, or .txt).
  • Environment: This is the “Brain” of the operation. It stores your configuration (like custom filters or global variables) and manages how templates are loaded and cached. You almost always initialize this once at the start of your script.
  • Template: This is the “Compiled Blueprint.” When you ask the Environment for a specific file, it returns a Template object. This object is what you actually use to “render” your final output by passing in data.

Install the package via pip:

Terminal window
pip install Jinja2 PyYAML
.
├── main.py # Execution engine
├── data.yml # Data source (Example 3)
└── templates/ # Blueprint folder
├── index.html # HTML Blueprint (Example 1)
├── message.txt # Text Blueprint (Example 2)
└── vhosts.j2 # Apache Blueprint (Example 3)

This script demonstrates how to load files from a folder and generate two different outputs simultaneously.

message.txt

Hello {{ name }}!
Welcome to {{ company }}.
Your status is: {% if active %}Active{% else %}Inactive{% endif %}

Index.html

<!DOCTYPE html>
<html>
<head><title>User Report</title></head>
<body>
<h1>Welcome, {{ user_name }}!</h1>
<p>Your tasks for today:</p>
<ul>
{% for task in tasks %}
<li>{{ task }}</li>
{% endfor %}
</ul>
</body>
</html>

The Script (main.py):

from jinja2 import Environment, FileSystemLoader
# Setup: Look for blueprints in /templates
env = Environment(loader=FileSystemLoader('templates'))
# The Data
data = {
"user_name": "Pavan",
"name": "Pavan",
"company": "EPAM",
"active": True,
"tasks": ["Fix Dockerfile", "Run Unit Tests"]
}
# 1. Generate HTML
html_out = env.get_template('index.html').render(data)
with open("final_report.html", "w") as f: f.write(html_out)
# 2. Generate Text
text_out = env.get_template('message.txt').render(data)
with open("result.txt", "w") as f: f.write(text_out)
print("HTML and Text files generated successfully.")

4. Example 3: YAML & Infrastructure as Code

Section titled “4. Example 3: YAML & Infrastructure as Code”

In production, data often comes from a YAML file. This example generates an Apache configuration (vhosts.conf) using structured data.

apache_vhosts:
- servername: www.domain-one.tld
documentroot: /www/domain-one
serveradmin: admin@domain-one.tld
- servername: www.domain-two.tld
documentroot: /www/domain-two

Step B: The Template (templates/vhosts.j2)

Section titled “Step B: The Template (templates/vhosts.j2)”
{% for vhost in apache_vhosts %}
<VirtualHost *:80>
ServerName {{ vhost.servername }}
DocumentRoot {{ vhost.documentroot }}
{% if vhost.serveradmin %}
ServerAdmin {{ vhost.serveradmin }}
{% endif %}
</VirtualHost>
{% endfor %}

Step C: The Execution Engine (main.py update)

Section titled “Step C: The Execution Engine (main.py update)”
import yaml
# 1. Load data from YAML
with open('data.yml') as f:
config_data = yaml.load(f, Loader=yaml.FullLoader)
# 2. Render the Apache config
vhost_template = env.get_template('vhosts.j2')
vhosts_conf = vhost_template.render(config_data)
# 3. Save output
with open('vhosts.conf', 'w') as f:
f.write(vhosts_conf)
print("Apache configuration generated from YAML.")

Output: vhost.conf

<VirtualHost *:80>
ServerName www.domain-one.tld
DocumentRoot /www/domain-one
ServerAdmin admin@domain-one.tld
</VirtualHost>
<VirtualHost *:80>
ServerName www.domain-two.tld
DocumentRoot /www/domain-two
</VirtualHost>

FeatureSyntaxUsage
Variable{{ var }}Print a value
Condition{% if var %}...{% endif %}Show text only if var is true
Loop{% for i in list %}...{% endfor %}Repeat text for every item
Filter\{\{ var|upper \}\}Change output (e.g., to uppercase)
LoadingFileSystemLoader('dir')Best practice for loading templates