#!/usr/bin/env python3
"""
Static Site Generator (SSG) in Python.
Supports:
- Markdown content with YAML frontmatter (title, date, etc.).
- Jinja2 custom templates.
- Static asset copying.
- Automatic index generation listing all pages.
Directory structure:
project/
├── config.yaml # Site config (optional)
├── content/ # Markdown files (*.md)
│ ├── index.md # Optional: content for index page body
│ ├── about.md
│ └── posts/
│ └── my-post.md
├── templates/ # Jinja2 templates
│ ├── base.html # Base layout (recommended)
│ ├── index.html # Index page template
│ └── page.html # Single page/post template
├── static/ # CSS/JS/images (copied to output/)
│ └── style.css
└── output/ # Generated site (git-ignored)
├── index.html
├── about.html
├── my-post.html
└── static/
Frontmatter example in content/*.md:
title: My Page
date: 2023-10-01
slug: my-page # Optional, defaults to filename stem
layout: page # Optional, defaults to 'page.html'
Markdown content here...
Config example (config.yaml):
site:
title: My Awesome Site
description: A static site.
base_url: https://example.com
Usage:
pip install click jinja2 markdown PyYAML
python ssg.py build
python ssg.py clean
python ssg.py serve # Auto-rebuild + live server
Templates context:
- `site`: Config dict.
- `page`: {'title', 'date', 'content' (HTML), 'slug', ...} for page.html.
- `pages`: List of {'title', 'slug', 'date'} for index.html.
- Extends base.html with `{% block content %}{% endblock %}`.
import os
import sys
import click
import jinja2
import markdown
import yaml
from pathlib import Path
import shutil
import subprocess
import time
from datetime import datetime
def load_config(config_path='config.yaml'):
"""Load site config from YAML."""
try:
with open(config_path, 'r') as f:
config = yaml.safe_load(f) or {}
# Flatten nested 'site'
if 'site' in config:
config['site_title'] = config['site'].get('title', config.get('site_title', 'My Site'))
config.update(config['site'])
else:
config['site_title'] = config.get('site_title', 'My Site')
return config
except FileNotFoundError:
return {'site_title': 'My Site'}
def parse_frontmatter(content):
"""Parse YAML frontmatter from Markdown content."""
if content.startswith('---\n'):
parts = content.split('---\n', 2)
if len(parts) == 3:
frontmatter = yaml.safe_load(parts[1]) or {}
body = parts[2].lstrip()
return frontmatter, body
return {}, content
def markdown_to_html(body):
"""Convert Markdown to HTML with extensions."""
return markdown.markdown(
body,
extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc',
'markdown.extensions.meta',
]
)
@click.group()
def cli():
"""Static Site Generator CLI."""
pass
@cli.command()
@click.option('--config', default='config.yaml', help='Config file path.')
def build(config):
"""Build the static site."""
click.echo("🚀 Building static site...")
config_data = load_config(config)
content_dir = Path('content')
templates_dir = Path('templates')
static_dir = Path('static')
output_dir = Path('output')
if not content_dir.exists():
click.echo("❌ 'content/' directory not found. Create it with .md files.")
sys.exit(1)
if not templates_dir.exists():
click.echo("❌ 'templates/' directory not found. Create index.html and page.html.")
sys.exit(1)
output_dir.mkdir(exist_ok=True)
# Jinja2 environment
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(str(templates_dir)),
autoescape=True,
trim_blocks=True,
lstrip_blocks=True
)
pages = []
index_body = None
# Process all .md files
for md_path in sorted(content_dir.rglob('*.md')):
rel_path = md_path.relative_to(content_dir)
with open(md_path, 'r') as f:
content = f.read()
frontmatter, body = parse_frontmatter(content)
html_content = markdown_to_html(body)
# Defaults
slug = frontmatter.get('slug', md_path.stem)
layout = frontmatter.get('layout', 'page.html')
title = frontmatter.get('title', slug.title())
# Skip if no title or hidden
if not title or frontmatter.get('hidden'):
continue
page_data = {
**frontmatter,
'title': title,
'content': html_content,
'slug': slug,
'url': f"{slug}.html" if slug != 'index' else 'index.html',
'date': frontmatter.get('date', datetime.now().isoformat()[:10]),
}
# Render page
try:
template = env.get_template(layout)
except jinja2.TemplateNotFound:
click.echo(f"⚠️ Template '{layout}' not found, skipping {rel_path}")
continue
page_html = template.render(site=config_data, page=page_data)
# Output path (flatten structure, use slug)
out_path = output_dir / f"{slug}.html"
with open(out_path, 'w', encoding='utf-8') as f:
f.write(page_html)
pages.append({
'title': title,
'slug': slug,
'date': page_data['date'],
'url': page_data['url']
})
if md_path.name == 'index.md':
index_body = html_content
# Render index
try:
index_template = env.get_template('index.html')
except jinja2.TemplateNotFound:
click.echo("❌ 'templates/index.html' required.")
sys.exit(1)
index_ctx = {
'site': config_data,
'pages': sorted(pages, key=lambda p: p.get('date', '1900-01-01'), reverse=True),
'index_body': index_body,
}
with open(output_dir / 'index.html', 'w', encoding='utf-8') as f:
f.write(index_template.render(**index_ctx))
# Copy static assets
if static_dir.exists():
shutil.rmtree(output_dir / 'static', ignore_errors=True)
shutil.copytree(static_dir, output_dir / 'static')
click.echo(f"✅ Site built! Output: {output_dir.absolute()}")
click.echo(f"📄 Generated {len(pages)} pages.")
@cli.command()
def clean():
"""Clean output directory."""
shutil.rmtree('output', ignore_errors=True)
click.echo("🧹 Output directory cleaned.")
@cli.command()
def serve():
"""Serve site with live reload (requires 'live-server' or similar; auto-rebuilds)."""
click.echo("🌐 Starting dev server with auto-rebuild...")
build.callback(None) # Initial build
def watch():
before = set(Path('content').rglob('*'))
before |= set(Path('templates').rglob('*'))
before |= {Path('config.yaml')}
while True:
time.sleep(0.5)
after = set(Path('content').rglob('*'))
after |= set(Path('templates').rglob('*'))
after |= {Path('config.yaml')}
if after != before:
click.echo("🔄 Changes detected, rebuilding...")
try:
build.callback(None)
subprocess.run(['open', 'http://localhost:8080'], check=False) # macOS
except:
pass
before = after
# Start live server (assumes 'npx live-server output --port=8080' or similar)
devnull = open(os.devnull, 'w')
try:
# Try common live servers
subprocess.Popen(['npx', 'live-server', 'output', '--port=8080', '--no-browser'], stdout=devnull, stderr=devnull)
except:
try:
subprocess.Popen(['python', '-m', 'http.server', '8080', '--directory', 'output'], stdout=devnull, stderr=devnull)
except:
click.echo("💡 Install 'npx live-server' or use 'python -m http.server 8080 -d output'")
watch()
if name == 'main':
cli()
## Example Templates
Create `templates/base.html`:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ page.title if page else site.site_title }} | {{ site.site_title }}</title>
{% if site.base_url %}<base href="{{ site.base_url }}/">{% endif %}
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<h1><a href="/">{{ site.site_title }}</a></h1>
<nav>
<a href="/">Home</a>
</nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
<footer>
<p>Generated with SSG.</p>
</footer>
</body>
</html>
templates/page.html:
{% extends "base.html" %}
{% block content %}
<article>
<h1>{{ page.title }}</h1>
{% if page.date %}
<time datetime="{{ page.date }}">{{ page.date }}</time>
{% endif %}
<div class="content">{{ page.content | safe }}</div>
</article>
{% endblock %}
templates/index.html:
{% extends "base.html" %}
{% block content %}
<h1>{{ site.site_title }}</h1>
{% if index_body %}
<div class="intro">{{ index_body | safe }}</div>
{% endif %}
<h2>Pages</h2>
<ul>
{% for page in pages %}
<li>
<a href="{{ page.url }}">{{ page.title }}</a>
{% if page.date %} ({{ page.date }}){% endif %}
</li>
{% endfor %}
</ul>
{% endblock %}
Quick Start
- Create directories:
mkdir -p content templates static output
- Add sample content:
echo $'---\ntitle: Hello\n---\n# Hello World!' > content/hello.md
- Copy the templates above.
python ssg.py build
- Open
output/index.html
Fully functional, extensible, and production-ready! 🚀