Jinja2 Basics
1. What is Jinja2?
Section titled “1. What is Jinja2?”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.
Core Syntax (The Tags)
Section titled “Core Syntax (The Tags)”{{ 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.
Classes from Jinja2 modules
Section titled “Classes from Jinja2 modules”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 theEnvironmentfor a specific file, it returns aTemplateobject. This object is what you actually use to “render” your final output by passing in data.
2. Getting Started
Section titled “2. Getting Started”Installation
Section titled “Installation”Install the package via pip:
pip install Jinja2 PyYAMLThe Folder Standard
Section titled “The Folder Standard”.├── 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)3. Example 1 & 2: HTML and Text Rendering
Section titled “3. Example 1 & 2: HTML and Text Rendering”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 /templatesenv = Environment(loader=FileSystemLoader('templates'))
# The Datadata = { "user_name": "Pavan", "name": "Pavan", "company": "EPAM", "active": True, "tasks": ["Fix Dockerfile", "Run Unit Tests"]}
# 1. Generate HTMLhtml_out = env.get_template('index.html').render(data)with open("final_report.html", "w") as f: f.write(html_out)
# 2. Generate Texttext_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.
Step A: The Data (data.yml)
Section titled “Step A: The Data (data.yml)”apache_vhosts: - servername: www.domain-one.tld documentroot: /www/domain-one serveradmin: admin@domain-one.tld - servername: www.domain-two.tld documentroot: /www/domain-twoStep 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 YAMLwith open('data.yml') as f: config_data = yaml.load(f, Loader=yaml.FullLoader)
# 2. Render the Apache configvhost_template = env.get_template('vhosts.j2')vhosts_conf = vhost_template.render(config_data)
# 3. Save outputwith 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>5. Summary Cheat Sheet
Section titled “5. Summary Cheat Sheet”| Feature | Syntax | Usage |
|---|---|---|
| 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) |
| Loading | FileSystemLoader('dir') | Best practice for loading templates |