2 min read

Static Site Generator with Jinja2

This guide demonstrates how to build a basic static site generator. It uses Jinja2, a powerful templating language for Python, to render HTML pages by combining templates with data.

Modules Used:

  • jinja2: To render HTML templates.
  • os: To handle file paths and directory creation.

Installation

pip install Jinja2

Project Structure

For this script to work, create a folder named templates in your project directory and add the following two files:

1. templates/base.html (The master layout)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }} - My Static Site</title>
    <style>
        body { font-family: sans-serif; margin: 2rem; }
        nav a { margin-right: 10px; text-decoration: none; color: blue; }
        footer { margin-top: 2rem; color: #666; font-size: 0.8rem; }
    </style>
</head>
<body>
    <nav>
        <a href="index.html">Home</a>
        <a href="about.html">About</a>
    </nav>
    <hr>

    {% block content %}{% endblock %}

    <hr>
    <footer>Generated on {{ date }}</footer>
</body>
</html>

2. templates/page.html (The content template)

{% extends "base.html" %}

{% block content %}
    <h1>{{ heading }}</h1>
    <p>{{ body }}</p>
{% endblock %}

The Code

Save this as build.py.

from jinja2 import Environment, FileSystemLoader
import os
from datetime import datetime

def build_site():
    # 1. Configuration
    output_dir = "site"
    template_dir = "templates"

    # Create output directory if it doesn't exist
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 2. Setup Jinja2 Environment
    env = Environment(loader=FileSystemLoader(template_dir))
    template = env.get_template("page.html")

    # 3. Define Content (The "Database")
    pages = [
        {
            "filename": "index.html",
            "title": "Home",
            "heading": "Welcome to My Site",
            "body": "This is a static site generated by Python and Jinja2."
        },
        {
            "filename": "about.html",
            "title": "About",
            "heading": "About Me",
            "body": "I am a Python developer who loves automation."
        }
    ]

    # 4. Render and Write Pages
    for page in pages:
        # Add dynamic context (like current date)
        page['date'] = datetime.now().strftime("%Y-%m-%d %H:%M")

        print(f"Generating {page['filename']}...")

        rendered_html = template.render(page)

        with open(os.path.join(output_dir, page['filename']), "w") as f:
            f.write(rendered_html)

    print(f"\nSuccess! Site generated in '{output_dir}/'")

if __name__ == "__main__":
    build_site()

Usage

  1. Ensure you have the templates folder created as described above.
  2. Run the script:
    python build.py
  3. Open the newly created site/index.html in your browser.

programming/python/python