Aller au contenu

Feuille de chaleur MkDocs

MkDocs - Documentation du projet avec marquage

MkDocs est un générateur de site statique rapide, simple et carrément magnifique qui est orienté vers la documentation de projet de construction. Les fichiers sources de documentation sont écrits dans Markdown, et configurés avec un seul fichier de configuration YAML.

Copier toutes les commandes Générer PDF

Sommaire

  • [Installation] (LINK_1)
  • [Pour commencer] (LINK_1)
  • [Structure du projet] (LINK_1)
  • [Configuration] (LINK_1)
  • [Documentation écrite] (LINK_1)
  • [Navigation] (LINK_1)
  • [Thèmes] (LINK_1)
  • [Plugins] (LINK_1)
  • [Extensions] (LINK_1)
  • [Déploiement] (LINK_1)
  • [Thèmes sur mesure] (LINK_1)
  • [Configuration avancée] (LINK_1)
  • [Internationalisation] (LINK_1)
  • Rechercher
  • [Documentation de l'API] (LINK_1)
  • [Performance] (LINK_1)
  • [Meilleures pratiques] (LINK_1)

Installation

Installation de Python

# Install Python (if not already installed)
# MkDocs requires Python 3.7+

# Check Python version
python --version
python3 --version

Installer MkDocs

# Install via pip
pip install mkdocs

# Install with additional dependencies
pip install mkdocs[i18n]

# Install specific version
pip install mkdocs==1.5.3

# Verify installation
mkdocs --version
```_

### Environnement virtuel (Recommandé)
```bash
# Create virtual environment
python -m venv mkdocs-env

# Activate virtual environment
# On Windows
mkdocs-env\Scripts\activate
# On macOS/Linux
source mkdocs-env/bin/activate

# Install MkDocs
pip install mkdocs

# Deactivate when done
deactivate
```_

### Installation de développement
```bash
# Install from source
git clone https://github.com/mkdocs/mkdocs.git
cd mkdocs
pip install -e .

# Install development dependencies
pip install -r requirements/dev.txt

Commencer

Créer un nouveau projet

# Create new MkDocs project
mkdocs new my-project

# Navigate to project directory
cd my-project

# Project structure created:
# my-project/
#   ├── docs/
#   │   └── index.md
#   └── mkdocs.yml

Commandes de base

# Start development server
mkdocs serve

# Start on custom port
mkdocs serve --dev-addr=127.0.0.1:8080

# Build static site
mkdocs build

# Build and clean output directory
mkdocs build --clean

# Deploy to GitHub Pages
mkdocs gh-deploy

Première documentation

<!-- docs/index.md -->
# Welcome to My Project

This is the homepage of my documentation.

## Features

- Easy to use
- Fast and responsive
- Beautiful themes

## Getting Started

Check out the [User Guide](user-guide.md) to get started.
# mkdocs.yml
site_name: My Project Documentation
site_description: A comprehensive guide to my project
site_author: Your Name
site_url: https://yourname.github.io/my-project

nav:
  - Home: index.md
  - User Guide: user-guide.md
  - API Reference: api.md

theme:
  name: material

Structure du projet

Structure de base

my-project/
├── docs/                 # Documentation source files
   ├── index.md         # Homepage
   ├── user-guide.md    # User guide
   ├── api.md           # API documentation
   ├── images/          # Images and assets
   └── stylesheets/     # Custom CSS
├── mkdocs.yml           # Configuration file
└── site/                # Generated site (after build)

Structure avancée

my-project/
├── docs/
   ├── index.md
   ├── getting-started/
      ├── index.md
      ├── installation.md
      └── quickstart.md
   ├── user-guide/
      ├── index.md
      ├── configuration.md
      └── advanced.md
   ├── api/
      ├── index.md
      ├── endpoints.md
      └── examples.md
   ├── assets/
      ├── images/
      ├── css/
      └── js/
   └── overrides/        # Theme overrides
├── mkdocs.yml
├── requirements.txt      # Python dependencies
└── .github/
    └── workflows/
        └── ci.yml        # GitHub Actions

Structure multilingue

my-project/
├── docs/
   ├── en/              # English documentation
      ├── index.md
      └── guide.md
   ├── es/              # Spanish documentation
      ├── index.md
      └── guide.md
   └── fr/              # French documentation
       ├── index.md
       └── guide.md
├── mkdocs.yml
├── mkdocs.es.yml        # Spanish config
└── mkdocs.fr.yml        # French config

Configuration

Configuration de base

# mkdocs.yml
site_name: My Project
site_description: A great project
site_author: Your Name
site_url: https://example.com

# Repository
repo_name: username/repository
repo_url: https://github.com/username/repository
edit_uri: edit/main/docs/

# Copyright
copyright: Copyright &copy; 2023 Your Name

# Navigation
nav:
  - Home: index.md
  - Getting Started:
    - Installation: getting-started/installation.md
    - Quick Start: getting-started/quickstart.md
  - User Guide:
    - Overview: user-guide/index.md
    - Configuration: user-guide/configuration.md
  - API Reference: api.md

# Theme
theme:
  name: material
  language: en

# Build
docs_dir: docs
site_dir: site

Configuration avancée

# mkdocs.yml
site_name: Advanced Project Documentation
site_description: Comprehensive documentation with advanced features
site_author: Your Name
site_url: https://docs.example.com

# Repository information
repo_name: username/project
repo_url: https://github.com/username/project
edit_uri: edit/main/docs/

# Copyright and legal
copyright: |
  Copyright &copy; 2023 <a href="https://example.com">Your Company</a><br>
  Licensed under <a href="https://opensource.org/licenses/MIT">MIT License</a>

# Navigation structure
nav:
  - Home: index.md
  - Getting Started:
    - Overview: getting-started/index.md
    - Installation: getting-started/installation.md
    - Quick Start: getting-started/quickstart.md
    - Configuration: getting-started/configuration.md
  - User Guide:
    - Introduction: user-guide/index.md
    - Basic Usage: user-guide/basic-usage.md
    - Advanced Features: user-guide/advanced.md
    - Troubleshooting: user-guide/troubleshooting.md
  - API Reference:
    - Overview: api/index.md
    - Authentication: api/auth.md
    - Endpoints: api/endpoints.md
    - Examples: api/examples.md
  - Development:
    - Contributing: development/contributing.md
    - Testing: development/testing.md
    - Release Notes: development/changelog.md

# Theme configuration
theme:
  name: material
  language: en
  palette:
    - scheme: default
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode
    - scheme: slate
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-4
        name: Switch to light mode
  font:
    text: Roboto
    code: Roboto Mono
  features:
    - navigation.tabs
    - navigation.sections
    - navigation.expand
    - navigation.top
    - search.highlight
    - search.share
    - content.code.copy

# Plugins
plugins:
  - search:
      lang: en
  - minify:
      minify_html: true
  - git-revision-date-localized:
      type: date

# Markdown extensions
markdown_extensions:
  - admonition
  - pymdownx.details
  - pymdownx.superfences
  - pymdownx.highlight:
      anchor_linenums: true
  - pymdownx.inlinehilite
  - pymdownx.snippets
  - pymdownx.tabbed:
      alternate_style: true
  - attr_list
  - md_in_html
  - tables
  - footnotes
  - toc:
      permalink: true

# Extra CSS and JavaScript
extra_css:
  - stylesheets/extra.css
  - stylesheets/custom.css

extra_javascript:
  - javascripts/extra.js
  - https://unpkg.com/mermaid@8.6.4/dist/mermaid.min.js

# Extra configuration
extra:
  social:
    - icon: fontawesome/brands/github
      link: https://github.com/username
    - icon: fontawesome/brands/twitter
      link: https://twitter.com/username
    - icon: fontawesome/brands/linkedin
      link: https://linkedin.com/in/username
  analytics:
    provider: google
    property: G-XXXXXXXXXX
  version:
    provider: mike

Environnement Configuration

# mkdocs.yml (base configuration)
site_name: My Project
docs_dir: docs
site_dir: site

# Development configuration
dev_addr: 127.0.0.1:8000
use_directory_urls: true

# Production configuration
site_url: https://docs.example.com
use_directory_urls: false

Documentation rédactionnelle

Bases de notation

# Heading 1
## Heading 2
### Heading 3

**Bold text**
*Italic text*
~~Strikethrough~~
`Inline code`

- Unordered list item 1
- Unordered list item 2
  - Nested item

1. Ordered list item 1
2. Ordered list item 2

[Link text](https://example.com)
[Internal link](user-guide.md)
[Link with title](https://example.com "Title")

![Image alt text](https://images/screenshot.png)
![Image with title](https://images/diagram.png "Diagram Title")

Blocs de codes

```python
def hello_world():
print("Bonjour, Monde!")
example.py
(nom)
"Bonjour, nom !"

print(greet("MkDocs"))
1
2
3
4
def fibonacci(n):
si n <= 1:
retour n
retour fibonacci(n-1) + fibonacci(n-2)

```python hl_lines=2 3" def process_data(data): clean_data = clean(data) # Cette ligne est surlignée résultat = analyse(nettoyé_données) # Cette ligne est surlignée résultat du retour

```»

### Tableaux
```markdown
|  |  |  | Feature | Description | Status |  |  |  |
| --- | --- | --- |
|  |  |  | Search | Full-text search | ✅ Complete |  |  |  |
|  |  |  | Themes | Multiple themes | ✅ Complete |  |  |  |
|  |  |  | Plugins | Extensible | 🚧 In Progress |  |  |  |

|  |  |  | Left Aligned | Center Aligned | Right Aligned |  |  |  |
| :--- | :---: | ---: |
|  |  |  | Left | Center | Right |  |  |  |
|  |  |  | Text | Text | Text |  |  |  |

Recommandations

!!! note
    This is a note admonition.

!!! tip "Custom Title"
    This is a tip with a custom title.

!!! warning
    This is a warning admonition.

!!! danger "Critical"
    This is a danger admonition with custom title.

!!! info "Information"
    This is an info admonition.

!!! success
    This is a success admonition.

!!! failure
    This is a failure admonition.

!!! question "FAQ"
    This is a question admonition.

??? note "Collapsible Note"
    This note is collapsible.

???+ tip "Expanded by Default"
    This tip is expanded by default.

Onglets de contenu

=== "Python"


```python
def bonjour():
print("Bonjour de Python!")
fonction hello() {
console.log("Bonjour de JavaScript!");
}
"Bonjour de Bash !"
### Notes
```markdown
This is a sentence with a footnote[^1].

Another sentence with a footnote[^note].

[^1]: This is the first footnote.
[^note]: This is a named footnote.
nav:
  - Home: index.md
  - About: about.md
  - Contact: contact.md
nav:
  - Home: index.md
  - Getting Started:
    - Installation: getting-started/installation.md
    - Quick Start: getting-started/quickstart.md
    - Configuration: getting-started/configuration.md
  - User Guide:
    - Overview: user-guide/index.md
    - Basic Usage: user-guide/basic.md
    - Advanced Usage: user-guide/advanced.md
  - API Reference:
    - Overview: api/index.md
    - Authentication: api/auth.md
    - Endpoints:
      - Users: api/endpoints/users.md
      - Posts: api/endpoints/posts.md
      - Comments: api/endpoints/comments.md
# Automatic navigation based on file structure
# Remove nav section to enable auto-generation

plugins:
  - awesome-pages:
      filename: .pages
      collapse_single_pages: true
      strict: false
# docs/.pages
nav:
  - index.md
  - getting-started
  - user-guide
  - api
  - ...
nav:
  - Home: index.md
  - Documentation:
    - User Guide: user-guide.md
    - API Reference: api.md
  - External Links:
    - GitHub: https://github.com/username/project
    - Issues: https://github.com/username/project/issues
    - Discussions: https://github.com/username/project/discussions

Thèmes

Matériau Thème

# Install Material theme
pip install mkdocs-material
# mkdocs.yml
theme:
  name: material
  palette:
    # Palette toggle for light mode
    - scheme: default
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode
    # Palette toggle for dark mode
    - scheme: slate
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-4
        name: Switch to light mode
  font:
    text: Roboto
    code: Roboto Mono
  features:
    - navigation.tabs
    - navigation.sections
    - navigation.expand
    - navigation.top
    - search.highlight
    - search.share
    - content.code.copy
    - content.code.annotate
  icon:
    repo: fontawesome/brands/github

Lire lesDocs Thème

theme:
  name: readthedocs
  highlightjs: true
  hljs_languages:
    - yaml
    - python
    - javascript

Configuration personnalisée du thème

theme:
  name: material
  custom_dir: overrides
  palette:
    primary: teal
    accent: orange
  font:
    text: Ubuntu
    code: Ubuntu Mono
  logo: assets/logo.png
  favicon: assets/favicon.ico
  features:
    - navigation.instant
    - navigation.tracking
    - navigation.tabs
    - navigation.tabs.sticky
    - navigation.sections
    - navigation.expand
    - navigation.indexes
    - navigation.top
    - search.highlight
    - search.share
    - search.suggest
    - header.autohide
    - content.code.copy
    - content.code.annotate

Changement de thème

theme:
  name: material
  palette:
    - media: "(prefers-color-scheme: light)"
      scheme: default
      primary: blue
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode
    - media: "(prefers-color-scheme: dark)"
      scheme: slate
      primary: blue
      toggle:
        icon: material/brightness-4
        name: Switch to light mode

Greffons

Greffons essentiels

# Install common plugins
pip install mkdocs-material
pip install mkdocs-minify-plugin
pip install mkdocs-git-revision-date-localized-plugin
pip install mkdocs-awesome-pages-plugin
pip install mkdocs-redirects

Plugin de recherche

plugins:
  - search:
      lang: 
        - en
        - es
|  |  | separator: '[\s\-,:!=\[\]()"/]+ | (?!\b)(?=[A-Z][a-z]) | \.(?!\d) | &[lg]t;' |  |  |
      prebuild_index: true

Greffon de date de révision Git

plugins:
  - git-revision-date-localized:
      type: date
      timezone: UTC
      locale: en
      fallback_to_build_date: false
      enable_creation_date: true

Minimiser le plugin

plugins:
  - minify:
      minify_html: true
      minify_js: true
      minify_css: true
      htmlmin_opts:
        remove_comments: true
      cache_safe: true

Impressionnant Plugin de pages

plugins:
  - awesome-pages:
      filename: .pages
      collapse_single_pages: true
      strict: false

Redirige le plugin

plugins:
  - redirects:
      redirect_maps:
        'old-page.md': 'new-page.md'
        'old-section/index.md': 'new-section/index.md'
        'legacy/': 'current/'

Configuration personnalisée du plugin

plugins:
  - search
  - minify:
      minify_html: true
  - git-revision-date-localized:
      type: datetime
      timezone: America/New_York
  - awesome-pages
  - redirects:
      redirect_maps:
        'changelog.md': 'development/changelog.md'
  - macros:
      module_name: docs/macros
  - mkdocstrings:
      handlers:
        python:
          options:
            docstring_style: google

Prorogations

Extensions PyMdown

# Install PyMdown Extensions
pip install pymdown-extensions
markdown_extensions:
  # Python Markdown
  - abbr
  - admonition
  - attr_list
  - def_list
  - footnotes
  - md_in_html
  - toc:
      permalink: true
      title: On this page
  - tables

  # PyMdown Extensions
  - pymdownx.arithmatex:
      generic: true
  - pymdownx.betterem:
      smart_enable: all
  - pymdownx.caret
  - pymdownx.details
  - pymdownx.emoji:
      emoji_generator: !!python/name:materialx.emoji.to_svg
      emoji_index: !!python/name:materialx.emoji.twemoji
  - pymdownx.highlight:
      anchor_linenums: true
      line_spans: __span
      pygments_lang_class: true
  - pymdownx.inlinehilite
  - pymdownx.keys
  - pymdownx.magiclink:
      repo_url_shorthand: true
      user: username
      repo: repository
  - pymdownx.mark
  - pymdownx.smartsymbols
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:pymdownx.superfences.fence_code_format
  - pymdownx.tabbed:
      alternate_style: true
  - pymdownx.tasklist:
      custom_checkbox: true
  - pymdownx.tilde

Mise en évidence du code

markdown_extensions:
  - pymdownx.highlight:
      anchor_linenums: true
      line_spans: __span
      pygments_lang_class: true
      auto_title: true
      linenums: true
  - pymdownx.inlinehilite
  - pymdownx.snippets:
      base_path: docs
      check_paths: true
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:pymdownx.superfences.fence_code_format

Appui aux mathématiques

markdown_extensions:
  - pymdownx.arithmatex:
      generic: true

extra_javascript:
  - javascripts/mathjax.js
  - https://polyfill.io/v3/polyfill.min.js?features=es6
  - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
// docs/javascripts/mathjax.js
window.MathJax = {
  tex: {
    inlineMath: [["\\(", "\\)"]],
    displayMath: [["\\[", "\\]"]],
    processEscapes: true,
    processEnvironments: true
  },
  options: {
    ignoreHtmlClass: ".*|",
    processHtmlClass: "arithmatex"
  }
};

document$.subscribe(() => {
  MathJax.typesetPromise()
})

Déploiement

Pages GitHub

# Deploy to GitHub Pages
mkdocs gh-deploy

# Deploy with custom commit message
mkdocs gh-deploy --message "Deploy documentation updates"

# Deploy to custom branch
mkdocs gh-deploy --remote-branch gh-pages

Actions GitHub

# .github/workflows/ci.yml
name: ci
on:
  push:
    branches:
      - master
      - main
permissions:
  contents: write
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v4
        with:
          python-version: 3.x
      - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
      - uses: actions/cache@v3
        with:
          key: mkdocs-material-${{ env.cache_id }}
          path: .cache
          restore-keys: |
            mkdocs-material-
      - run: pip install mkdocs-material
      - run: mkdocs gh-deploy --force

Netlifier

# netlify.toml
[build]
  publish = "site"
  command = "mkdocs build"

[build.environment]
  PYTHON_VERSION = "3.8"

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

Vercel

{
  "builds": [
    {
      "src": "mkdocs.yml",
      "use": "@vercel/python"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/site/$1"
    }
  ]
}

Déploiement Docker

# Dockerfile
FROM python:3.9-slim

WORKDIR /docs

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

EXPOSE 8000

CMD ["mkdocs", "serve", "--dev-addr=0.0.0.0:8000"]
# docker-compose.yml
version: '3.8'
services:
  mkdocs:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - .:/docs
    environment:
      - PYTHONUNBUFFERED=1

Domaine personnalisé

# mkdocs.yml
site_url: https://docs.example.com

extra:
  social:
    - icon: fontawesome/brands/github
      link: https://github.com/username/project
# CNAME file for GitHub Pages
echo "docs.example.com" > docs/CNAME

Thèmes personnalisés

Structure du thème

custom_theme/
├── 404.html
├── base.html
├── content.html
├── nav.html
├── nav-sub.html
├── search.html
├── toc.html
├── css/
   ├── base.css
   └── bootstrap.min.css
├── js/
   ├── base.js
   └── bootstrap.min.js
└── img/
    └── favicon.ico

Modèle de base

<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    {% if page_description %}
    <meta name="description" content="{{ page_description }}">
    {% endif %}

    {% if site_author %}
    <meta name="author" content="{{ site_author }}">
    {% endif %}

    {% if canonical_url %}
    <link rel="canonical" href="{{ canonical_url }}">
    {% endif %}

    <link rel="shortcut icon" href="{{ 'img/favicon.ico'|url }}">

    <title>{% if page_title %}{{ page_title }} - {% endif %}{{ site_name }}</title>

    <link href="{{ 'css/bootstrap.min.css'|url }}" rel="stylesheet">
    <link href="{{ 'css/base.css'|url }}" rel="stylesheet">

    {% for path in config['extra_css'] %}
    <link href="{{ path|url }}" rel="stylesheet">
    {% endfor %}
</head>

<body>
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container">
            <!-- Navigation content -->
            {% include "nav.html" %}
        </div>
    </div>

    <div class="container">
        <div class="row">
            {% if nav %}
            <div class="col-md-3">
                {% include "toc.html" %}
            </div>
            <div class="col-md-9" role="main">
            {% else %}
            <div class="col-md-12" role="main">
            {% endif %}
                {% include "content.html" %}
            </div>
        </div>
    </div>

    <script src="{{ 'js/jquery.min.js'|url }}"></script>
    <script src="{{ 'js/bootstrap.min.js'|url }}"></script>
    <script src="{{ 'js/base.js'|url }}"></script>

    {% for path in config['extra_javascript'] %}
    <script src="{{ path|url }}"></script>
    {% endfor %}
</body>
</html>

Modèle de contenu

<!-- content.html -->
{% if meta.source %}
<div class="source-links">
    {% for filename in meta.source %}
        <span class="label label-primary">{{ filename }}</span>
    {% endfor %}
</div>
{% endif %}

{{ page.content }}

{% if page and page.edit_url %}
<div class="edit-page">
    <a href="{{ page.edit_url }}" class="btn btn-default">
        <i class="fa fa-edit"></i> Edit this page
    </a>
</div>
{% endif %}

{% if page and page.next_page %}
<div class="pagination">
    <a href="{{ page.next_page.url|url }}" class="btn btn-primary">
        Next: {{ page.next_page.title }}
    </a>
</div>
{% endif %}

Modèle de navigation

<!-- nav.html -->
<div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="{{ nav.homepage.url|url }}">{{ site_name }}</a>
</div>

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        {% for nav_item in nav %}
            {% if nav_item.children %}
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        {{ nav_item.title }} <b class="caret"></b>
                    </a>
                    <ul class="dropdown-menu">
                        {% for nav_item in nav_item.children %}
                            <li>
                                <a href="{{ nav_item.url|url }}">{{ nav_item.title }}</a>
                            </li>
                        {% endfor %}
                    </ul>
                </li>
            {% else %}
                <li {% if nav_item.active %}class="active"{% endif %}>
                    <a href="{{ nav_item.url|url }}">{{ nav_item.title }}</a>
                </li>
            {% endif %}
        {% endfor %}
    </ul>

    {% if config.repo_url %}
    <ul class="nav navbar-nav navbar-right">
        <li>
            <a href="{{ config.repo_url }}" class="navbar-link">
                <i class="fa fa-github"></i> GitHub
            </a>
        </li>
    </ul>
    {% endif %}
</div>

Configuration avancée

Configuration multi-site

# mkdocs.yml (main site)
site_name: Main Documentation
site_url: https://docs.example.com

nav:
  - Home: index.md
  - API: api/
  - Guides: guides/

plugins:
  - multirepo:
      cleanup: true
      keep_docs_dir: true
      repos:
        - name: api-docs
          import_url: https://github.com/username/api-docs
          imports: [
            docs/api.md,
            docs/endpoints/
          ]

Variables d'environnement

# mkdocs.yml
site_name: !ENV [SITE_NAME, 'Default Site Name']
site_url: !ENV SITE_URL

extra:
  version: !ENV VERSION
  api_url: !ENV [API_URL, 'https://api.example.com']

Configuration conditionnelle

# mkdocs.yml
site_name: My Documentation

# Development configuration
dev_addr: !ENV [DEV_ADDR, '127.0.0.1:8000']

# Production configuration
site_url: !ENV SITE_URL

plugins:
  - search
  - !ENV [ANALYTICS_PLUGIN, 'null']

extra:
  analytics: !ENV [ANALYTICS_CONFIG, {}]

Crochets personnalisés

# hooks.py
import os
from mkdocs.plugins import BasePlugin

class CustomHook(BasePlugin):
    def on_pre_build(self, config):
        """Run before the build starts"""
        print("Starting build...")

    def on_post_build(self, config):
        """Run after the build completes"""
        print("Build completed!")

    def on_page_markdown(self, markdown, page, config, files):
        """Process page markdown"""
        # Add custom processing
        return markdown

    def on_page_content(self, html, page, config, files):
        """Process page HTML content"""
        # Add custom processing
        return html
# mkdocs.yml
plugins:
  - search
  - hooks:
      hooks:
        - hooks.py

Internationalisation

Configuration multilingue

# mkdocs.yml
plugins:
  - i18n:
      default_language: en
      languages:
        en:
          name: English
          build: true
        es:
          name: Español
          build: true
        fr:
          name: Français
          build: true
      nav_translations:
        es:
          Home: Inicio
          Getting Started: Comenzando
          User Guide: Guía del Usuario
        fr:
          Home: Accueil
          Getting Started: Commencer
          User Guide: Guide Utilisateur

Spécifique à la langue Contenu

<!-- docs/index.md -->
# Welcome

{% if config.theme.language == 'es' %}
¡Bienvenido a nuestra documentación!
{% elif config.theme.language == 'fr' %}
Bienvenue dans notre documentation!
{% else %}
Welcome to our documentation!
{% endif %}

Structure de traduction

docs/
├── en/
   ├── index.md
   ├── getting-started.md
   └── user-guide.md
├── es/
   ├── index.md
   ├── comenzando.md
   └── guia-usuario.md
└── fr/
    ├── index.md
    ├── commencer.md
    └── guide-utilisateur.md

Rechercher

Configuration de recherche locale

plugins:
  - search:
      lang: 
        - en
        - es
        - fr
|  |  | separator: '[\s\-,:!=\[\]()"/]+ | (?!\b)(?=[A-Z][a-z]) | \.(?!\d) | &[lg]t;' |  |  |
      min_search_length: 2
      prebuild_index: python
      indexing: 'full'

Intégration de la recherche externe

# Algolia DocSearch
extra_javascript:
  - https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js
  - javascripts/search.js

extra_css:
  - https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css
// docs/javascripts/search.js
docsearch({
  apiKey: 'your-api-key',
  indexName: 'your-index-name',
  inputSelector: '#search-input',
  debug: false
});

Recherche personnalisée

<!-- overrides/partials/search.html -->
<div class="md-search" data-md-component="search" role="dialog">
  <label class="md-search__overlay" for="__search"></label>
  <div class="md-search__inner" role="search">
    <form class="md-search__form" name="search">
      <input type="text" class="md-search__input" name="query" 
             placeholder="Search documentation" autocapitalize="off" 
             autocorrect="off" autocomplete="off" spellcheck="false" 
             data-md-component="search-query">
      <label class="md-search__icon md-icon" for="__search">
        <svg viewBox="0 0 24 24"><path d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z"></path></svg>
      </label>
      <nav class="md-search__options" aria-label="Search">
        <button type="reset" class="md-search__icon md-icon" tabindex="-1">
          <svg viewBox="0 0 24 24"><path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"></path></svg>
        </button>
      </nav>
    </form>
    <div class="md-search__output">
      <div class="md-search__scrollwrap" data-md-scrollfix>
        <div class="md-search-result" data-md-component="search-result">
          <div class="md-search-result__meta">
            Initializing search
          </div>
          <ol class="md-search-result__list"></ol>
        </div>
      </div>
    </div>
  </div>
</div>

Documentation API

Auto-généré API Docs

# Install mkdocstrings
pip install mkdocstrings[python]
# mkdocs.yml
plugins:
  - mkdocstrings:
      handlers:
        python:
          options:
            docstring_style: google
            show_source: true
            show_root_heading: true
            show_root_toc_entry: true
            show_object_full_path: false
            show_category_heading: true
            group_by_category: true
            heading_level: 2
<!-- docs/api.md -->
# API Reference

## Core Module

::: myproject.core
    options:
      show_source: false
      heading_level: 3

## Utilities

::: myproject.utils
    options:
      members:
        - helper_function
        - UtilityClass

Intégration OpenAPI

# Install mkdocs-swagger-ui-tag
pip install mkdocs-swagger-ui-tag
# mkdocs.yml
plugins:
  - swagger-ui-tag

markdown_extensions:
  - swagger-ui-tag
<!-- docs/api.md -->
# API Documentation

## REST API

{% swagger-ui src="openapi.yaml" %}

Documentation manuelle de l'API

# API Reference

## Authentication

All API requests require authentication using an API key.

```http
GET /api/v1/utilisateurs
Autorisation : Au porteur

Endpoints

GET /api/v1/users

Retrieve a list of users.

Parameters:

| | | | Parameter | Type | Required | Description | | | | | --- | --- | --- | --- | | | | | limit | integer | No | Maximum number of users to return (default: 10) | | | | | | | | offset | integer | No | Number of users to skip (default: 0) | | | |

Response:

{
"utilisateurs": [
{
"id": 1,
"nom" : "John Doe",
"email": "john@exemple.com"
}
Les
"total": 100,
"limite": 10,
"offset": 0
}

Example:

boucle -H "Autorisation: Porte ton_API_KEY" \
«_______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
## Rendement

### Optimisation de la construction
```yaml
# mkdocs.yml
plugins:
  - search:
      prebuild_index: python
  - minify:
      minify_html: true
      minify_js: true
      minify_css: true
      cache_safe: true
  - optimize:
      enabled: !ENV [OPTIMIZE, false]
      print_page_size: true
      print_pure_css_size: true
      print_js_size: true

extra:
  generator: false  # Remove "Made with Material for MkDocs"

Stratégie de mise en cache

# mkdocs.yml
plugins:
  - search:
      prebuild_index: true
  - git-revision-date-localized:
      enable_creation_date: true
      fallback_to_build_date: false

extra:
  version:
    provider: mike
    default: latest

Optimisation de l'image

# Install image optimization tools
pip install mkdocs-img2fig-plugin
pip install mkdocs-optimize-plugin
# mkdocs.yml
plugins:
  - img2fig
  - optimize:
      enabled: !ENV [OPTIMIZE, false]
      optimize_png: true
      optimize_jpg: true
      optimize_svg: true

Chargement paresseux

<!-- Custom image component -->
<img src="{{ image_url }}" 
     alt="{{ alt_text }}" 
     loading="lazy"
     decoding="async">

Meilleures pratiques

Organisation du contenu

# Recommended structure
docs/
├── index.md              # Homepage
├── getting-started/       # Getting started guide
   ├── index.md
   ├── installation.md
   └── quickstart.md
├── user-guide/           # Detailed user guide
   ├── index.md
   ├── basic-usage.md
   └── advanced-features.md
├── api/                  # API documentation
   ├── index.md
   ├── authentication.md
   └── endpoints.md
├── development/          # Development docs
   ├── contributing.md
   ├── testing.md
   └── changelog.md
├── assets/              # Images and files
   ├── images/
   ├── css/
   └── js/
└── overrides/           # Theme customizations

Rédaction des meilleures pratiques

  • Utiliser des rubriques claires pour une meilleure navigation
  • Inclure des exemples de code avec une syntaxe appropriée
  • Ajouter des captures d'écran pour le guidage visuel
  • Écrire des descriptions concises pour mieux comprendre
  • ** Utiliser un formatage cohérent** sur toutes les pages
  • ** Inclure les renvois** entre les sujets connexes

SEO Optimisation

# mkdocs.yml
site_name: Your Project Documentation
site_description: Comprehensive documentation for Your Project
site_author: Your Name
site_url: https://docs.yourproject.com

extra:
  social:
    - icon: fontawesome/brands/github
      link: https://github.com/username/project
    - icon: fontawesome/brands/twitter
      link: https://twitter.com/username

plugins:
  - meta
  - sitemap:
      change_frequency: daily
      priority: 1.0

Pratiques exemplaires de maintenance

  • ** Mises à jour régulières** pour maintenir le contenu à jour
  • Contrôle des liens pour prévenir les ruptures de liens
  • Surveillance du rendement pour les temps de construction
  • Rétroaction de l'utilisateur intégration pour les améliorations
  • Contrôle de la version pour les modifications de documentation
  • ** Tests automatisés** pour les constructions de documentation

Résumé

MkDocs est un puissant générateur de site statique spécialement conçu pour la documentation de projet. Les principales caractéristiques sont les suivantes :

  • Basé sur Markdown: écrire la documentation en simple Markdown
  • Python-puissant: Extensible avec les plugins Python
  • Soutien au thème: De beaux thèmes dont le design des matériaux
  • Aperçu en direct: Aperçu en temps réel pendant le développement
  • ** Déploiement facile** : Déploiement simple sur différentes plateformes
  • Écosystà ̈me de Plugin: Riche écosystème de plugins pour une fonctionnalité étendue
  • Intégration de la recherche: Recherche intégrée avec support de recherche externe
  • Multi-langue : appui à l'internationalisation

En suivant les meilleures pratiques et en tirant parti des capacités de MkDocs, vous pouvez créer une documentation professionnelle et durable qui sert efficacement vos utilisateurs et se développe avec votre projet.