Comprehending the Objective
I'm focusing on defining the scope: Python will be the backbone, crafting an SSG. Markdown fuels the content, while HTML templates, possibly Jinja2, handle the visual layout. The architecture is becoming clearer; my grasp of the project's parameters deepens.
Structuring the Pipeline
I'm now mapping out the core steps: Read, Parse Markdown (plus frontmatter), Template, and Output. The directory structure will dictate content input. Processing involves both parsing Markdown and integrating metadata. Jinja2 templates will be the visual layer, and the final output must accurately reflect the structure of the source directory.
Mapping the Workflow
I'm now detailing the application's phases. Setup involves folder creation. Content processing involves recursive directory walks, Markdown parsing (with python-frontmatter), and template rendering using Jinja2. Static assets are handled via a simple copy operation. I'm focusing on the code's structural organization.
Codifying the Logic
I'm translating the architectural steps into Python code, starting with imports, config, and the build_site function, establishing the file structure, and setting up the Jinja2 environment. Now, I'm focusing on the core file processing loop, including parsing Markdown and frontmatter, template selection, and output directory maintenance. The structure is coming together!
Outlining the Structure
I'm presently building the core functionality: The project starts with understanding the need for parsing Markdown, loading frontmatter, and Jinja2 templating. I am defining and refining directory operations (creating outputs, copying assets). The logic for recursive directory parsing is being written to handle Markdown files and associated frontmatter. The CLI wrapper is also taking shape.
Conceptualizing the Implementation
I'm now detailing the planned implementation, addressing setup (directory structure and initial project files), template loading (Jinja2 configuration), and content processing involving recursive directory traversal, markdown parsing and template rendering. I also need to provide the user with the directory layout and dependencies. Static asset handling is also being fleshed out.
Formulating the Script
I am now focusing on coding the structure and the main script. The script should be modular and function-based. First, gather the project structure (directory structure) and the file contents to provide context for the user. Then, address the use of templates. After that, I will define the main logic for processing and rendering the information. I will also incorporate an example for the homepage to list all the other posts.
This is a project-based guide. We will build a lightweight Static Site Generator (SSG) named "PyGen".
We will use three key libraries to make this work efficiently:
markdown: To convert content to HTML.
python-frontmatter: To parse metadata (like titles and dates) from the top of Markdown files.
jinja2: For powerful HTML templating.
1. Project Structure
First, create a folder for your project and set up this directory structure:
my_ssg/
├── content/ # Your Markdown files go here
│ ├── index.md
│ └── hello-world.md
├── templates/ # Your Jinja2 HTML templates
│ ├── base.html
│ └── post.html
├── static/ # CSS, Images, JS
│ └── style.css
├── public/ # The generated output (do not create manually)
├── main.py # The logic script
└── requirements.txt # Dependencies
2. Install Dependencies
Create a requirements.txt file:
markdown==3.4.4
python-frontmatter==1.0.0
Jinja2==3.1.2
Install them via terminal:
pip install -r requirements.txt
3. The Generator Logic (main.py)
This script runs in two passes:
- Collection: It reads all files to gather metadata (useful for generating a "Recent Posts" list).
- Generation: It renders the logic and writes HTML files.
import os
import shutil
from datetime import datetime
import markdown
import frontmatter
from jinja2 import Environment, FileSystemLoader
# Configuration
CONTENT_DIR = 'content'
OUTPUT_DIR = 'public'
TEMPLATE_DIR = 'templates'
STATIC_DIR = 'static'
def clean_output_directory():
"""Removes the public directory to start fresh."""
if os.path.exists(OUTPUT_DIR):
shutil.rmtree(OUTPUT_DIR)
os.makedirs(OUTPUT_DIR)
def copy_static_files():
"""Copies static assets like CSS and images."""
if os.path.exists(STATIC_DIR):
# Copy static folder into public/static
shutil.copytree(STATIC_DIR, os.path.join(OUTPUT_DIR, STATIC_DIR))
def load_content():
"""
Reads markdown files, parses frontmatter, and returns a list of dictionaries.
"""
posts = []
# Walk through the content directory
for root, _, files in os.walk(CONTENT_DIR):
for file in files:
if file.endswith(".md"):
filepath = os.path.join(root, file)
# Parse Frontmatter and Markdown
post = frontmatter.load(filepath)
# Convert Markdown body to HTML
html_content = markdown.markdown(post.content)
# Calculate relative web path (e.g., content/blog/post.md -> blog/post.html)
rel_path = os.path.relpath(filepath, CONTENT_DIR)
filename_html = os.path.splitext(rel_path)[0] + ".html"
# Store data object
posts.append({
'metadata': post.metadata,
'content': html_content,
'path': filename_html,
'filename': file
})
# Sort posts by date (if present in metadata), newest first
posts.sort(key=lambda x: x['metadata'].get('date', ''), reverse=True)
return posts
def generate_site(posts):
"""
Takes the list of posts and converts them to HTML files using Jinja2.
"""
# Setup Jinja2 Environment
env = Environment(loader=FileSystemLoader(TEMPLATE_DIR))
for post in posts:
# Determine which template to use (default to 'post.html')
template_name = post['metadata'].get('template', 'post.html')
template = env.get_template(template_name)
# Render the template
# We pass 'posts' so any page can list all other pages (like a blog index)
rendered_html = template.render(
content=post['content'],
meta=post['metadata'],
posts=posts
)
# Define output path
output_path = os.path.join(OUTPUT_DIR, post['path'])
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Write file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(rendered_html)
print(f"Successfully generated {len(posts)} pages in '{OUTPUT_DIR}/'.")
def main():
print("Building site...")
clean_output_directory()
copy_static_files()
try:
all_posts = load_content()
generate_site(all_posts)
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
4. Create Files to Test It
Now, let's fill in the templates, content, and static folders so you can see it work.
The Templates
templates/base.html (The master layout using Jinja inheritance)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ meta.title }} | My Python SSG</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<nav>
<a href="/index.html">Home</a>
</nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
<footer>
<p>Generated by Python</p>
</footer>
</body>
</html>
templates/post.html (The standard page logic)
{% extends "base.html" %}
{% block content %}
<article>
<h1>{{ meta.title }}</h1>
<p class="date">{{ meta.date }}</p>
<hr>
{{ content | safe }}
</article>
{% endblock %}
templates/home.html (Special layout for the homepage seeing all posts)
{% extends "base.html" %}
{% block content %}
<h1>{{ meta.title }}</h1>
{{ content | safe }}
<h2>Recent Posts</h2>
<ul>
{% for post in posts %}
<!-- Don't list the homepage itself -->
{% if post.path != 'index.html' %}
<li>
<span class="date">{{ post.metadata.date }}</span>
<a href="/{{ post.path }}">{{ post.metadata.title }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
{% endblock %}
The Content (Markdown)
content/index.md
---
title: Welcome to My Site
date: 2023-10-27
template: home.html
---
This is the homepage. It uses a specific template (`home.html`) that knows how to list other posts loop logic defined in Jinja.
content/hello-world.md
---
title: Hello World
date: 2023-10-26
author: John Doe
---
## This is a subtitle
Here is some standard markdown content.
- List item 1
- List item 2
[Click here](https://google.com) to leave.
The Static Style
static/style.css
body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
nav a { margin-right: 15px; text-decoration: none; color: #333; font-weight: bold;}
.date { color: #888; font-size: 0.9em; }
5. Run It
- Open your terminal in the project folder.
- Run the script:
python main.py
- Look at the newly created
public/ folder.
- Open
public/index.html in your web browser.
Key Features Explained
- Frontmatter Parsing: The
--- block at the top of the Markdown files is converted into a Python dictionary (meta). We pass this to Jinja. This allows you to define custom variables like template, author, or tags.
- Template Selection: notice in
index.md we specified template: home.html. The Python script checks for this key; if it's missing, it defaults to post.html.
- Context Passing: In
main.py, the line posts=posts passes the entire list of site pages to every single page. This allows any page to generate a navigation menu or a "Recent Posts" list.