Markdown: conversion HTML en batch, avec template

On va enrichir le script pour que chaque fichier Markdown converti soit inséré dans un modèle HTML de base.

    6tq 5ttr 6ttr
  • Découverte

Lire le template depuis un fichier .html rend ton script plus clair et facile à maintenir (tu peux modifier le style sans toucher au Python).


Étape 1 — Créer un fichier template

Par exemple dans templates/base.html :

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>{title}</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 40px auto;
      line-height: 1.6;
      padding: 0 15px;
    }
    h1, h2, h3 {
      color: #2c3e50;
    }
    pre {
      background: #f4f4f4;
      padding: 10px;
      overflow-x: auto;
    }
    code {
      background: #eee;
      padding: 2px 4px;
      border-radius: 3px;
    }
    table {
      border-collapse: collapse;
      margin: 1em 0;
      width: 100%;
    }
    th, td {
      border: 1px solid #ccc;
      padding: 6px 12px;
      text-align: left;
    }
  </style>
</head>
<body>
{content}
</body>
</html>

Étape 2 — Script Python

import os
from markdown_it import MarkdownIt

# Parser Markdown
md = MarkdownIt("gfm-like")

INPUT_DIR = "articles"
OUTPUT_DIR = "html"
TEMPLATE_FILE = "templates/base.html"

# Charger le template une fois
with open(TEMPLATE_FILE, "r", encoding="utf-8") as f:
    TEMPLATE = f.read()

# Crée dossier de sortie
os.makedirs(OUTPUT_DIR, exist_ok=True)

# Parcourir les fichiers Markdown
for filename in os.listdir(INPUT_DIR):
    if filename.endswith(".md"):
        path_md = os.path.join(INPUT_DIR, filename)

        # Lire contenu Markdown
        with open(path_md, "r", encoding="utf-8") as f:
            contenu = f.read()

        # Convertir en HTML
        contenu_html = md.render(contenu)

        # Titre = nom du fichier (sans extension)
        titre = filename.replace(".md", "")

        # Injecter dans le template
        page_html = TEMPLATE.format(title=titre, content=contenu_html)

        # Nom du fichier de sortie
        output_name = filename.replace(".md", ".html")
        path_html = os.path.join(OUTPUT_DIR, output_name)

        # Écrire le HTML
        with open(path_html, "w", encoding="utf-8") as f:
            f.write(page_html)

        print(f"✅ {filename}{output_name}")

Avantages

  • Le template HTML est séparé → tu peux facilement modifier le design.
  • Le script Python est plus court et se concentre sur la logique d’import/conversion.
  • Tu peux créer plusieurs templates (par ex. base.html, blog.html, cours.html) et choisir lequel utiliser dans le script.

Pour aller plus loin