Designing Python static site generator with plugin hooks
Outlined a simple static site generator using markdown and Jinja2 with plugin support for pre-build and post-build events, showing a core generator class, dynamic plugin loading from a folder, content processing with metadata, and usage examples for plugins and site structure.
Below is a minimal, extensible static site generator scaffold in Python that:
- Walks a
content/ tree for .md files
- Converts Markdown → HTML using
markdown
- Renders HTML into a Jinja2 template
- Copies output to
dist/ (or configurable)
- Supports plugins with
pre_build and post_build hooks
You can expand it as needed (e.g., add more hooks, filters, asset copying, etc.).
Project layout
your_site/
├─ generator.py
├─ content/
│ ├─ index.md
│ └─ about.md
├─ templates/
│ └─ base.html
├─ plugins/
│ ├─ sample_plugin.py
│ └─ another_plugin.py
└─ dist/ # generated output (created automatically)
Requirements
pip install jinja2 markdown
If you want YAML front matter, also install python-frontmatter or use markdown’s meta extension as shown below.
generator.py
import os
import sys
import shutil
import importlib.util
from pathlib import Path
import markdown
from jinja2 import Environment, FileSystemLoader
class StaticSiteGenerator:
def __init__(
self,
content_dir="content",
template_dir="templates",
output_dir="dist",
plugins_dir="plugins",
):
self.content_dir = Path(content_dir)
self.template_dir = Path(template_dir)
self.output_dir = Path(output_dir)
self.plugins_dir = Path(plugins_dir)
# Jinja2 environment
self.env = Environment(loader=FileSystemLoader(str(self.template_dir)))
self.plugins = []
def load_plugins(self):
"""Dynamically load plugins from the plugins/ directory."""
sys.path.insert(0, str(self.plugins_dir))
for plugin_path in self.plugins_dir.glob("*.py"):
spec = importlib.util.spec_from_file_location(
plugin_path.stem, plugin_path
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
self.plugins.append(module)
def run_hooks(self, hook_name, **kwargs):
"""Run a named hook on all plugins, if present."""
for plugin in self.plugins:
hook = getattr(plugin, hook_name, None)
if callable(hook):
hook(self, **kwargs)
def clean_output(self):
"""Delete and recreate output directory."""
if self.output_dir.exists():
shutil.rmtree(self.output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
def build(self):
"""Main build pipeline."""
# pre-build
self.run_hooks("pre_build")
self.clean_output()
md = markdown.Markdown(extensions=["extra", "meta"])
for md_file in self.content_dir.rglob("*.md"):
rel_path = md_file.relative_to(self.content_dir)
out_path = self.output_dir / rel_path.with_suffix(".html")
out_path.parent.mkdir(parents=True, exist_ok=True)
with md_file.open("r", encoding="utf-8") as f:
source = f.read()
# Convert markdown to HTML
html = md.reset().convert(source)
# Extract metadata from "meta" extension
metadata = {}
if hasattr(md, "Meta"):
# Meta values come as list of strings by default
metadata = {
key.lower(): " ".join(val) if isinstance(val, list) else val
for key, val in md.Meta.items()
}
# Choose template: default to base.html
template_name = metadata.get("template", "base.html")
template = self.env.get_template(template_name)
# Render template
context = {
"content": html,
"meta": metadata,
"source_path": md_file,
"output_path": out_path,
}
rendered = template.render(**context)
# Write to output
with out_path.open("w", encoding="utf-8") as f:
f.write(rendered)
# post-build
self.run_hooks("post_build")
if __name__ == "__main__":
generator = StaticSiteGenerator()
generator.load_plugins()
generator.build()
Example template: templates/base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>{{ meta.title if meta.title else 'My Site' }}</title>
</head>
<body>
<header>
<h1>{{ meta.title if meta.title else 'My Site' }}</h1>
</header>
<main>
{{ content | safe }}
</main>
<footer>
<small>Generated by StaticSiteGenerator</small>
</footer>
</body>
</html>
Example content: content/index.md
Title: Home Page
template: base.html
# Welcome!
This is the **home page** generated from Markdown.
Sample plugin: plugins/sample_plugin.py
def pre_build(generator, **kwargs):
print("[sample_plugin] Running pre-build hook.")
# You could, for instance, add a Jinja2 filter dynamically:
def shout(s):
return str(s).upper()
generator.env.filters["shout"] = shout
def post_build(generator, **kwargs):
print("[sample_plugin] Running post-build hook.")
# Example: generate a list of output files
outputs = list(generator.output_dir.rglob("*.html"))
print(f"[sample_plugin] Generated {len(outputs)} HTML files.")
Another plugin example: plugins/cleanup_plugin.py
import shutil
def pre_build(generator, **kwargs):
# Clean or back up the output dir before build
backup_dir = generator.output_dir.with_suffix(".bak")
if backup_dir.exists():
shutil.rmtree(backup_dir)
if generator.output_dir.exists():
generator.output_dir.rename(backup_dir)
print("[cleanup_plugin] Backed up previous dist/ to dist.bak/")
def post_build(generator, **kwargs):
print("[cleanup_plugin] Build complete!")
Running
python generator.py
After running, HTML files will appear under dist/. Extend the pipeline by adding more hooks and plugin functions (e.g., pre_render_page, post_render_page, etc.), or add static asset copying. You can also register Jinja2 filters in plugins as shown.