Saltar a contenido

MkDocs Cheatsheet

  • Documentación del proyecto con marcador realizado/h1 "Clase de inscripción" MkDocs es un generador de sitio estático rápido, sencillo y vertical que está diseñado para construir la documentación del proyecto. Los archivos fuente de documentación están escritos en Markdown y configurados con un solo archivo de configuración YAML. ▪/p] ■/div titulada
########################################################################################################################################################################################################################################################## Copiar todos los comandos
########################################################################################################################################################################################################################################################## Generar PDF seleccionado/button

■/div titulada ■/div titulada

Cuadro de contenidos

Instalación

Instalación Python

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

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

Instalar 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

Medio ambiente virtual (recomendado)

# 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

Instalación de desarrollo

# 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

Comienzo

Crear un nuevo proyecto

# 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

Comandos básicos

# 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

Primera documentación

<!-- 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

Estructura del proyecto

Estructura básica

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)

Estructura avanzada

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

Estructura de lenguaje múltiple

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

Configuración

Configuración básica

# 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

Configuración avanzada

# 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

Medio ambiente específico Configuración

# 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

Documentación de escritura

Básicos de marcado

# 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")

Bloqueos de código

```python
def hello_world():
print("Hola, Mundo!")
example.py
def salud(nombre):
¡Hola!

print(greet("MkDocs")
1
2
3
4
def fibonacci(n):
si no
retorno n
retorno fibonacci(n-1) + fibonacci(n-2)
def process_data(data):
cleaned_data = clean(data) # This line is highlighted
resultado = análisis(cleaned_data) # This line is highlighted
Resultado de retorno
__CODE_BLOCK_19_

### Cuadros
```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 |  |  |  |  |

Admoniciones

!!! 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.

Índice

=== "Python"


```python
def hola():
print("Hola de Python!")
función hola() {}
consola.log("Hola desde JavaScript!");
}
"Hola de Bash!"
### Notas de pie de página
```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

Temas

Material Tema

# 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

ReadTheDocs Tema

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

Configuración temática personalizada

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

Cambio de tema

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

Plugins

Plugins esenciales

# 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

Búsqueda Plugin

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

Git Revision Date Plugin

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

Minify Plugin

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

Awesome Pages Plugin

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

Redirects Plugin

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

### Configuración de plugin personalizado
```yaml
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

Extensiones

PyMdown Extensiones

# 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

Code Highlighting

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

Apoyo a las matemáticas

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
```_

```javascript
// docs/javascripts/mathjax.js
window.MathJax = {
  tex: {
    inlineMath: [["\\(", "\\)"]],
    displayMath: [["\\[", "\\]"]],
    processEscapes: true,
    processEnvironments: true
  },
  options: {
    ignoreHtmlClass: ".*|",
    processHtmlClass: "arithmatex"
  }
};

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

Despliegue

Páginas de 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

GitHub Actions

# .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

Netlify

# 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"
    }
  ]
}

Docker Deployment

# 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

Dominio personalizado

# 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

Temas personalizados

Estructura temática

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

Plantilla 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>

Plantilla de contenido

<!-- 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 %}

Plantilla de navegación

<!-- 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>

Configuración avanzada

Configuración multi-sitio

# 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/
          ]

Medio ambiente

# 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']

Configuración condicional

# 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, {}]

Ganchos personalizados

# 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
```_

## Internacionalización

### Configuración en varios idiomas
```yaml
# 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

Idiomas específicos Índice

<!-- 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 %}

Estructura de traducción

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

Búsqueda

Configuración de búsqueda local

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'

Integración de búsqueda externa

# 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
});

Búsqueda personalizada

<!-- 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>

Documentación de API

Docs de API autogenerados

# 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

OpenAPI Integration

# 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" %}

Documentación de API manual

__CODE_BLOCK_79_http Obtener /api/v1/usuarios Authorization: Bearer YOU_API_KEY __CODE_BLOCK_80_json {} "usuarios": {} "id": 1, "nombre": "John Doe", "email": "john@example.com" } ] "total": 100, "limit": 10, "offset": 0 }

**Example:**

```bash
curl -H "Authorization: Bearer YOU_API_KEY" \
"

## Ejecución

### Optimización de la construcción
```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"

Caching Strategy

# 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

Optimización de imagen

# Install image optimization tools
pip install mkdocs-img2fig-plugin
pip install mkdocs-optimize-plugin
```_

```yaml
# mkdocs.yml
plugins:
  - img2fig
  - optimize:
      enabled: !ENV [OPTIMIZE, false]
      optimize_png: true
      optimize_jpg: true
      optimize_svg: true

Lazy Cargando

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

Buenas prácticas

Content Organization

# 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

Escribir las mejores prácticas

  • Utilizar las partidas claras para una mejor navegación
  • Include code examples with proper syntax highlighting
  • Añadir capturas de pantalla para orientación visual
  • Write concise descriptions for better understanding
  • Use formato consistente en todas las páginas
  • Incluir referencias cruzadas entre temas relacionados

SEO Optimización

# 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

Mejores prácticas de mantenimiento

  • ** Actualizaciones periódicas** para mantener el contenido actual
  • Comprobación de enlaces para evitar los enlaces rotos
  • ** Supervisión de la ejecución** para tiempos de construcción
  • Reacción de los usuarios integración para mejoras
  • Control de verificación para los cambios de documentación
  • ** Pruebas automáticas** para la construcción de documentación

-...

Resumen

MkDocs es un potente generador de sitios estáticos diseñado específicamente para la documentación del proyecto. Las características principales incluyen:

  • Con base en marketing: Escriba la documentación en simple marcación
  • Python-powered: Extensible con plugins Python
  • Apoyo temático: Hermosos temas incluyendo el diseño de material
  • Vive vista previa: Previsualización en tiempo real durante el desarrollo
  • Easy deployment: Implementación sencilla en varias plataformas
  • Ecosistema de plugin: Ecosistema rico de plugins para funcionalidad extendida
  • Integración de búsqueda: Búsqueda incorporada con soporte de búsqueda externa
  • Multi-language: Apoyo a la internacionalización

Al seguir las mejores prácticas y aprovechar las capacidades de MkDocs, puede crear documentación profesional y mantenible que sirva a sus usuarios con eficacia y crezca con su proyecto.

" copia de la funciónToClipboard() {} comandos const = document.querySelectorAll('code'); que todos losCommands = '; comandos. paraCada(cmd = confianza allCommands += cmd.textContent + '\n'); navigator.clipboard.writeText(allCommands); alerta ('Todos los comandos copiados a portapapeles!'); }

función generaPDF() { ventana.print(); } ■/script título