DEV Community

Cover image for Build a Static Site Generator in Python
Muhammad Saud
Muhammad Saud

Posted on Originally published at logicstack.org

Build a Static Site Generator in Python

A static site generator turns plain text files into a finished website. It reads Markdown posts, fills HTML templates with their content, and writes out plain HTML files that any web server can serve. In this tutorial we build one with Python, Markdown, and Jinja2 in about 120 lines, and we run every step so you can see the real output.

Key takeaways

  • A static site generator separates content (Markdown files) from layout (HTML templates), so changing the design never touches the writing.
  • python-frontmatter splits the YAML header from the Markdown body in one call.
  • Python-Markdown converts Markdown to HTML, and the fenced_code and tables extensions handle code blocks and tables.
  • Jinja2 template inheritance keeps one shared layout for every page on the site.
  • The whole site builds to plain files in public/, so any static host can serve it with no server code at all.

What we build

We build a small blog generator called build.py. It reads Markdown posts from content/posts/, skips any post marked as a draft, converts each one to HTML, wraps it in a shared page template, and writes the result into public/. It also builds an index page that lists every post newest first, copies a stylesheet into place, and generates an RSS feed so readers can follow the blog. The finished site is plain files: no database, no server code, nothing to install on the host.

The project layout looks like this:

ssg/
  build.py
  content/
    posts/
      hello-world.md
      why-build-own-tools.md
  templates/
    base.html
    post.html
    index.html
  static/
    style.css
  public/            # generated output goes here
Enter fullscreen mode Exit fullscreen mode

Prerequisites

You need Python 3.10 or newer and a terminal. We tested this tutorial with Python 3.12.3. Everything else comes from three small packages: markdown for Markdown to HTML, Jinja2 for templates, and python-frontmatter for reading the YAML header at the top of each post.

Step 1: Set up the project and install the packages

Create the folders and a virtual environment, then install the three packages:

mkdir -p ssg/content/posts ssg/templates ssg/static
cd ssg
python3 -m venv venv
venv/bin/pip install markdown Jinja2 python-frontmatter
Enter fullscreen mode Exit fullscreen mode

Our install gave us Markdown 3.11.4, Jinja2 3.1.6, and python-frontmatter 1.3.0. Pin those versions in a requirements.txt file if you want the same build on another machine.

Step 2: Write two sample posts with front matter

Each post is a Markdown file with a YAML block at the top, between two --- lines. That block is called front matter, and it holds the post title and date. The body below it is plain Markdown. Save this as content/posts/hello-world.md:

---
title: Hello, Static World
date: 2026-12-01
---

This is our first post. It has **bold text**, a [link](https://example.com), and a table:

| Feature | Status |
| ------- | ------ |
| Markdown | Working |
| Templates | Working |

Enter fullscreen mode Exit fullscreen mode


python
print("Hello from a code block")

Enter fullscreen mode Exit fullscreen mode


markdown

Add a second post, content/posts/why-build-own-tools.md, dated 2026-11-28, and a third file with draft: true in its front matter. The draft post tests our filter: it must never appear in the output.

Step 3: Create the templates

Jinja2 templates keep the shared layout in one place. templates/base.html holds the page skeleton with two blocks that child templates fill in:



  {% block title %}{{ site_title }}{% endblock %}



    [{{ site_title }}](/index.html)
    [RSS](/rss.xml)


    {% block content %}{% endblock %}

  Built with our tiny static site generator.

Enter fullscreen mode Exit fullscreen mode


plaintext

The post template extends that base and fills both blocks. Note the | safe filter: Jinja2 escapes HTML by default, so without it the converted Markdown would show up as escaped text instead of real headings and paragraphs.

{% extends "base.html" %}
{% block title %}{{ post.title }} | {{ site_title }}{% endblock %}
{% block content %}

  {{ post.title }}
  {{ post.date }}
  {{ post.html | safe }}

{% endblock %}
Enter fullscreen mode Exit fullscreen mode


plaintext

The index template is simpler. It loops over the posts and links to each one:

{% extends "base.html" %}
{% block content %}
Latest posts

  {% for post in posts %}
  - [{{ post.title }}](/{{ post.slug }}.html) {{ post.date }}

  {% endfor %}

{% endblock %}
Enter fullscreen mode Exit fullscreen mode


markdown

How does the build script work?

The build script has three jobs: load the posts, render them through the templates, and write the files. Save this as build.py:

"""Tiny static site generator: Markdown posts + Jinja2 templates -> HTML site."""

import shutil
from datetime import date, datetime
from pathlib import Path

import frontmatter
import markdown
from jinja2 import Environment, FileSystemLoader

ROOT = Path(__file__).parent
CONTENT_DIR = ROOT / "content" / "posts"
TEMPLATE_DIR = ROOT / "templates"
STATIC_DIR = ROOT / "static"
OUTPUT_DIR = ROOT / "public"
SITE_TITLE = "The Tiny Blog"
SITE_URL = "https://example.com"

MD_EXTENSIONS = ["fenced_code", "tables"]

def load_posts(content_dir=CONTENT_DIR):
    """Read every .md file, skip drafts, return posts sorted newest first."""
    posts = []
    for md_file in sorted(content_dir.glob("*.md")):
        post = frontmatter.load(md_file)
        if post.get("draft"):
            continue
        meta = dict(post.metadata)
        meta["slug"] = meta.get("slug") or md_file.stem
        raw_date = meta.get("date")
        if isinstance(raw_date, str):
            meta["date"] = datetime.strptime(raw_date, "%Y-%m-%d").date()
        elif isinstance(raw_date, datetime):
            meta["date"] = raw_date.date()
        elif raw_date is None:
            meta["date"] = date.today()
        meta["html"] = markdown.markdown(post.content, extensions=MD_EXTENSIONS)
        posts.append(meta)
    posts.sort(key=lambda p: p["date"], reverse=True)
    return posts

def render_rss(posts):
    """Build a small RSS 2.0 feed from the post list."""
    items = []
    for post in posts:
        items.append(
            f"""
{post["title"]}
{SITE_URL}/{post["slug"]}.html
{post["date"].strftime("%a, %d %b %Y 00:00:00 +0000")}
""")
    return (
        '\n'
        '\n'
        f"{SITE_TITLE}\n"
        f"{SITE_URL}\n"
        "Posts from the tiny blog.\n"
        + "\n".join(items)
        + "\n\n"
    )

def build():
    """Render every post, the index page, the RSS feed, and copy static files."""
    if OUTPUT_DIR.exists():
        shutil.rmtree(OUTPUT_DIR)
    OUTPUT_DIR.mkdir(parents=True)
    if STATIC_DIR.exists():
        shutil.copytree(STATIC_DIR, OUTPUT_DIR / "static")

    env = Environment(loader=FileSystemLoader(TEMPLATE_DIR))
    post_template = env.get_template("post.html")
    index_template = env.get_template("index.html")

    posts = load_posts()
    for post in posts:
        html = post_template.render(post=post, site_title=SITE_TITLE)
        (OUTPUT_DIR / f"{post['slug']}.html").write_text(html)
    (OUTPUT_DIR / "index.html").write_text(
        index_template.render(posts=posts, site_title=SITE_TITLE)
    )
    (OUTPUT_DIR / "rss.xml").write_text(render_rss(posts))
    print(f"Built {len(posts)} post(s) into {OUTPUT_DIR}/")
    for post in posts:
        print(f"  {post['date']}  {post['slug']}.html")

if __name__ == "__main__":
    build()
Enter fullscreen mode Exit fullscreen mode


markdown

Three details do the heavy lifting. First, frontmatter.load() returns both the YAML metadata and the Markdown body in one call. Second, load_posts() skips drafts and sorts the rest newest first, so the index page is always in the right order. Third, the date handling covers all three shapes a YAML date can arrive in: a string, a datetime, or nothing, in which case today is used.

Why keep content and layout apart?

Because the two change for different reasons. Writers edit Markdown files without touching HTML, and designers restyle the templates without touching a single post. That split is the whole idea behind every static site generator, from Jekyll and Hugo down to this 120 line script. It also makes the build easy to test: the Markdown conversion is a pure function, and template rendering is just data plus a file name.

Step 5: Add a stylesheet

Save a small static/style.css with basic typography and spacing. The build script copies the whole static/ folder into public/static/, so any file you add there ships with the site. Ours is about 20 lines: a centred column, a header rule, muted dates, and a grey background for code.

Step 6: Run the build and check the output

Run the script:

venv/bin/python build.py
Enter fullscreen mode Exit fullscreen mode


plaintext

Our run printed exactly this:

Built 2 post(s) into /home/hatch/workspace/practical-tutorials/static-site-generator/public/
  2026-12-01  hello-world.html
  2026-11-28  why-build-own-tools.html
Enter fullscreen mode Exit fullscreen mode

Two posts built, and the draft post is nowhere in public/. The output folder holds five files: the two post pages, index.html, rss.xml, and the copied stylesheet. The index page lists the newer post first, and the RSS feed parses as valid XML with both posts in it.

What did testing catch?

Our first build had a real bug. The sample post started with its own # Hello, Static World heading, and the post template also renders the title as an h1. The page came out with two top level headings, which is wrong for both readers and search engines. The fix is simple: the title lives in the front matter and the template renders it, so the Markdown body must not repeat it. We removed the heading from both sample posts, rebuilt, and each page now has exactly one h1. Keep this rule in every post you write: title in front matter, body starts with prose.

Step 7: Serve the site and verify it in a browser

Python ships a web server in the standard library, so no extra install is needed. Add a --serve flag to build.py that builds first and then serves public/ on port 8000, or run python3 -m http.server 8000 --directory public from the project folder. We checked all four URLs with curl and every one returned HTTP 200: the index page, the post page, the RSS feed, and the stylesheet.

What to try next

First, add a tags field to the front matter and build one page per tag, so readers can browse by topic. Second, add pagination to the index page once you pass ten posts, so the home page stays short. Third, deploy the public/ folder to a static host such as GitHub Pages or Render, and add a file watcher so the site rebuilds every time you save a post.


Originally published on LogicStack. Run the code examples right in your browser with our free interactive Python and SQL playgrounds — no setup, no sign-up.

Top comments (1)

Collapse
 
alexshev profile image
Alex Shev •

The content-template-output split is a great first project because every generated artifact stays inspectable. A build manifest listing each source file, output path, and content hash would be a useful next addition: it makes stale outputs and incremental rebuilds easy to reason about.