The user wants a static site generator (SSG) in Python.
The core requirements are:
- Markdown support: It needs to parse Markdown files into HTML.
- Custom templates: It needs to use a templating engine (like Jinja2) to wrap the content in HTML structure.
Key Components of a Static Site Generator:
- Configuration: A place to define input/output directories, site title, etc.
- Content Parsing:
- Read files from a source directory (e.g.,
content/).
- Extract metadata (Front Matter: title, date, layout) and body content.
- Convert Markdown body to HTML.
- Templating:
- Load layout files (e.g.,
templates/).
- Inject content and metadata into the templates.
- File Writing:
- Save the resulting HTML to an output directory (e.g.,
output/ or public/).
- Preserve directory structure (optional but good).
- Asset Handling (Optional but practical): Copy CSS, images, etc.
Technology Stack:
- Language: Python (as requested).
- Markdown Parsing:
markdown or mistune (standard library doesn't do Markdown). markdown is very common.
- Templating:
Jinja2 is the industry standard for Python templating.
- Front Matter:
python-frontmatter is great for parsing YAML headers in Markdown files. Alternatively, regex or string manipulation can be used for a "from scratch" feel, but libraries are better for robustness. To keep it simple and dependency-light (or at least standard), I'll use python-frontmatter and markdown and Jinja2.
Plan/Structure:
-
Project Directory Structure:
content/ (Markdown files)
templates/ (HTML files)
static/ (CSS/JS)
output/ (Generated site)
build.py (The script)
-
Step-by-Step Implementation:
- Setup: Imports (
os, shutil, markdown, jinja2, frontmatter).
- Load Config: Simple constants or a dict.
- Load Templates: Setup Jinja2 environment.
- Process Content:
- Walk the
content directory.
- Read file.
- Parse front matter (title, date, template name).
- Convert Markdown body to HTML.
- Render:
- Select template based on metadata.
- Render with context (content, metadata, config).
- Write Output:
- Determine output path (handle
index.md vs page.md).
- Write HTML file.
- Copy Static Files.
-
Refining the "From Scratch" aspect vs "Library" aspect:
- Using
markdown, jinja2, and python-frontmatter is the "Pythonic" way to do it. Writing a Markdown parser from scratch is outside the scope of a single prompt usually, and writing a template engine from scratch is error-prone. I will assume using libraries is acceptable/preferred.
-
Drafting the Code (Mental or Scratchpad):
-
Imports:
import os
import shutil
import markdown
import frontmatter
from jinja2 import Environment, FileSystemLoader
-
Main Loop:
Iterate through content/.
If .md:
Load with frontmatter.load().
Convert body with markdown.markdown().
Get template name from meta (default to 'base.html').
Render with Jinja.
Write to output/.
-
The Template:
Needs blocks: {% block content %}{% endblock %}.
Variables: {{ content }}, {{ title }}.
-
The Markdown File:
---
title: Hello World
date: 2023-01-01
---
# Header
text...
-
Adding Polish:
- Error handling (check if template exists).
- Cleaning the output directory before build.
- Handling nested directories (permalink structure).
-
Final Output Structure:
- Prerequisites:
pip install markdown jinja2 python-frontmatter
- The Code:
ssg.py
- Directory Setup: Explain how to create the folders.
- Example Content:
content/post.md, templates/base.html.
- Running it.
-
Self-Correction/Review during drafting:
- Issue: URLs. If I have
content/blog/post.md, does it become output/blog/post.html? Yes, os.path.relpath helps here.
- Issue:
index.md should probably map to index.html in that specific folder, or post.md to post/index.html (pretty URLs).
- Decision: To keep the code understandable, I will stick to a 1:1 mapping:
content/about.md -> output/about.html.
-
Writing the prompt response:
- Start with the requirements (libraries).
- Provide the directory structure.
- Provide the Python script.
- Provide the sample template and markdown.
- Explain how to run it.
This looks solid. It solves the user's request effectively using standard Python practices.
Here is a complete, lightweight static site generator built in Python. It uses Jinja2 for templating and Python-Markdown to convert text files.
Prerequisites
You will need to install two libraries via your terminal:
pip install markdown jinja2 python-frontmatter
- markdown: Converts Markdown syntax to HTML.
- jinja2: A powerful templating engine for Python (handles
{{ variables }} and {% blocks %}).
- python-frontmatter: Parses the metadata (title, date, layout) at the top of your Markdown files.
The Project Structure
Create a folder for your project and set it up like this:
my_ssg/
├── build.py # The generator script
├── content/ # Your Markdown pages
│ └── index.md
├── templates/ # HTML layouts
│ └── base.html
└── output/ # Generated site (created automatically)
1. Create the Content (content/index.md)
The top section between --- is called "Front Matter". It holds metadata we can use in templates.
---
title: My First Post
date: 2023-10-27
layout: base.html
---
# Hello World!
This is my **first** paragraph using Markdown.
* Item 1
* Item 2
2. Create the Template (templates/base.html)
This uses Jinja2 syntax. The {{ content }} variable will be replaced by the converted Markdown, and {{ title }} will be replaced by the front matter data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
hr { border: 1px solid #eee; margin: 2rem 0; }
</style>
</head>
<body>
<header>
<h1>{{ title }}</h1>
<small>Published: {{ date }}</small>
</header>
<hr>
<main>
{{ content }}
</main>
<footer>
<p>© 2023 My Python SSG</p>
</footer>
</body>
</html>
3. The Generator Script (build.py)
This script reads the content, processes the data, renders the HTML, and writes it to the output folder.
import os
import shutil
import markdown
import frontmatter
from jinja2 import Environment, FileSystemLoader
# Configuration
CONTENT_DIR = 'content'
OUTPUT_DIR = 'output'
TEMPLATE_DIR = 'templates'
def clean_output():
"""Remove old build files and recreate directory."""
if os.path.exists(OUTPUT_DIR):
shutil.rmtree(OUTPUT_DIR)
os.makedirs(OUTPUT_DIR)
def load_templates():
"""Setup Jinja2 environment."""
return Environment(loader=FileSystemLoader(TEMPLATE_DIR))
def process_markdown(file_path, env):
"""
1. Read Markdown file.
2. Parse Front Matter (metadata) and Content.
3. Convert Markdown to HTML.
4. Render Template with data.
"""
with open(file_path, 'r', encoding='utf-8') as f:
# frontmatter.load splits the file into metadata and content
post = frontmatter.load(f)
# Extract metadata
meta = post.metadata
content_text = post.content
# Convert Markdown to HTML
md_converter = markdown.Markdown(extensions=['extra', 'meta'])
html_content = md_converter.convert(content_text)
# Determine which template to use (default to base.html)
template_name = meta.get('layout', 'base.html')
template = env.get_template(template_name)
# Combine data for the template
# We pass 'content' (the HTML) and all metadata items (title, date, etc.)
data = {
'content': html_content,
**meta
}
return template.render(data)
def build_site():
print("Building site...")
clean_output()
env = load_templates()
# Iterate over all files in content directory
for root, dirs, files in os.walk(CONTENT_DIR):
for filename in files:
if filename.endswith('.md'):
input_path = os.path.join(root, filename)
# Calculate output path (.md -> .html)
relative_path = os.path.relpath(input_path, CONTENT_DIR)
output_filename = os.path.splitext(relative_path)[0] + '.html'
output_path = os.path.join(OUTPUT_DIR, output_filename)
# Ensure subdirectories exist in output
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Process and Render
print(f"Processing: {input_path} -> {output_path}")
rendered_html = process_markdown(input_path, env)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(rendered_html)
print("Site built successfully!")
if __name__ == "__main__":
build_site()
4. Run It
Run the script from your terminal:
python build.py
5. Result
Open the newly created output/index.html in your browser. You will see a rendered HTML page where the variables were replaced and the Markdown was converted to formatted text.
How to Extend This
To make this a full-featured SSG, you could add:
- Static Assets: Add logic to copy a
static/ folder (CSS, Images) to the output/ folder.
- Blog List: Loop through all posts in
build_site() to generate an index.html that lists all article titles and links.
- Configuration: Move
CONTENT_DIR and SITE_NAME into a config.py or settings.yaml file.
- Live Reload: Use Python's
http.server module to serve the output folder and watch for file changes to trigger a rebuild automatically.