Skip to content

MkDocs

MkDocs是一个快速、简单的静态站点生成器,适用于构建项目文档,其中文档使用 Markdown 格式编写,并且使用 yaml 格式的配置文档来进行配置。

安装

MkDocs 是由 Python 编写的:

Bash
# pip
pip install mkdocs

# conda
conda install -c conda-forge mkdocs

基本使用

  1. 创建项目
Bash
mkdocs new my_project

之后会在当前目录创建一个 my_project 文件夹其中包括:

Bash
mkdocs.yml
    docs/
        index.md
  • mkdocs.yml: MkDocs 配置文件
  • docs/: MkDocs 中源文档的保存目录
  1. 预览,MkDocs 内置了一个开发服务器能够让我们实时预览文档
Bash
mkdocs serve
# 预览 http://127.0.0.1:8000
  1. 构建静态网页
Bash
mkdocs build

运行该命令之后会在项目根目录下创建 sites 目录:

Bash
$ ls site
about  fonts  index.html  license  search.html
css    img    js          mkdocs   sitemap.xml

只需要将该文件夹复制到 web 服务器的部署目录就可以了。

MkDocs 配置

MkDocs 使用 yaml 格式的 mkdocs.yml 作为配置文件。

主题

MkDocs 内置了两个主题: mkdocs 和 readthedocs。不过我们更推荐使用第三方主题mkdocs-material,而且设置也是和该主题强相关的:

  1. 安装
Bash
# pip
pip install mkdocs-material

# conda
conda install -c conda-forge mkdocs-material
  1. 配置

同样在 mkdocs.yml 中添加来执行配置:

YAML
theme:
  name: mkdocs

MkDocs 的源文档都是基于 Markdown 文件的,并且放置到 /docs 目录中,还有其中任何以 . 开头的都会被忽略。

MkDocs 的 Markdown 渲染是由python-markdown库提供的

这些源文档需要在配置文件中(mkdocs.yml)中的 nav 字段中来定义,只有被定义在其中的 Markdown 文档才能够在导航栏上显示链接,而没有定义在其中的页面被隐式隐藏(只能作为内链使用):

YAML
nav:
  - Home: "index.md"
  - About: "about.md"

导航也可以通过子标题的形式来创建, 这里需要注意的是包含子标题的父标题不允许指定 md:

YAML
nav:
  - Home: "index.md"
  - "User Guide":
      - page/user_guide.md # 比较特殊的一种定义方式,title 作为名称
      - "Writing your docs": "writing-your-docs.md"
      - "Styling your docs": "styling-your-docs.md"
  - About:
      - "License": "license.md"
      - "Release Notes": "release-notes.md"

material 主题还对导航栏指定了一些可配置项:

YAML
theme:
  name: material # mkdocs-material
  features:
    - navigation.instant # 即时加载
    - navigation.instant.progress # 加载进度指示器
    - navigation.tabs # nav 显示在顶部,默认是左侧
    - navigation.tabs.sticky # nav 导航始终可见
    - toc.follow # 侧边栏根据内容自动滚动
    - navigation.top # 返回顶部
    - navigation.indexes # 显示 Section index 页面

MetaData

通过在 MarkDown 文件的顶部以--- 开始和结束来包装 YAML 格式的文本来为文档添加元数据,这些能够被 MkDocs 以及插件使用:

Markdown
---
title: My Document
summary: A brief description of my document.
authors:
  - Waylan Limberg
  - Tom Christie
date: 2018-07-10
some_url: https://example.com
---

# Title

This is the first paragraph of the document.

Markdown 扩展

最初 Markdown 由John Gruber实现,而meterial 主题会使用Python-MarkdownPyMdown Extensions来扩展 Markdown 语法提供更多的表现。

Tips

mkdocs 支持的扩展可以在mkdocs 插件列表中查看

标注(Admonitions)

标注是包含 icon 和 content 的用于展示附带内容的最佳选择。

将下面添加到 mkdocs.yml 来开启标注:

YAML
# 启用 markdown 扩展
markdown_extensions:
  - admonition
  - pymdownx.details
  - pymdownx.superfences

# 定义 icon
theme:
  icon:
    admonition:
      note: octicons/tag-16 # 注意
      abstract: octicons/checklist-16 # 简介
      info: octicons/info-16 # 信息
      tip: octicons/squirrel-16 # 提示
      success: octicons/check-16 # 成功
      question: octicons/question-16 # 问题
      warning: octicons/alert-16 # 警告
      failure: octicons/x-circle-16 # 失败
      danger: octicons/zap-16 # 危险
      bug: octicons/bug-16 # 错误
      example: octicons/beaker-16 # 示例
      quote: octicons/quote-16 # 引文

!!! <icon> 之后回车,也可以使用 ??? <icon> 开头,它会自动折叠,内容和标记必须空行且至少四个空格:

Markdown
!!! note

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod
    nulla. Curabitur feugiat, tortor non consequat finibus, justo purus auctor
    massa, nec semper lorem quam in massa.

Note

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla. Curabitur feugiat, tortor non consequat finibus, justo purus auctor massa, nec semper lorem quam in massa.

Note

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla. Curabitur feugiat, tortor non consequat finibus, justo purus auctor massa, nec semper lorem quam in massa.

注解(Annotations)

注解可以在任何地方添加一个小图标,点击或者鼠标悬停能够展开 一段提示。

将下面添加到 mkdocs.yml 来开启注解:

YAML
markdown_extensions:
  - attr_list
  - md_in_html
  - pymdownx.superfences

注解有点类似脚注,在需要标记的地方标记 (<num>) 之后在底部定义 1. content:

Markdown
Lorem ipsum dolor sit amet, (1) consectetur adipiscing elit.
{ .annotate }

1.  I'm an annotation! I can contain `code`, **formatted
    text**, images, ... basically anything that can be expressed in Markdown.

Lorem ipsum dolor sit amet, (1) consectetur adipiscing elit.

  1. I'm an annotation! I can contain code, formatted text, images, ... basically anything that can be expressed in Markdown.

注解能够定义在标注、选项卡等其他插件中

代码块(Code blocks)

主要是提供代码的高亮、文件名称显示、代码复制按钮等。

将下面添加到 mkdocs.yml 来开启代码块:

YAML
markdown_extensions:
  - pymdownx.highlight:
      anchor_linenums: true
      line_spans: __span
      pygments_lang_class: true
  - pymdownx.inlinehilite
  - pymdownx.snippets
  - pymdownx.superfences

三个反引号后跟语言名称,这也是标准的 Markdown 语法。他还可以通过 title='test.py' 来添加标题:

Markdown
```py title="bubble_sort.py"
def bubble_sort(items):
    for i in range(len(items)):
        for j in range(len(items) - 1 - i):
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]
```

渲染效果:

bubble_sort.py
def bubble_sort(items):
    for i in range(len(items)):
        for j in range(len(items) - 1 - i):
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]

Tip

高亮由 pygments 模块提供,他支持语言参考Pygments Language

选项卡(tabs)

将不同类型的内容分组在不同的选项卡下,最常见的就是描述同一个效果的不同语言的 API。

将下面添加到 mkdocs.yml 来开启选项卡:

YAML
markdown_extensions:
  - pymdownx.superfences
  - pymdownx.tabbed:
      alternate_style: true

通过 === <tab> 来定义标签:

Markdown
=== "C"

    ``` c
    #include <stdio.h>

    int main(void) {
      printf("Hello world!\n");
      return 0;
    }
    ```

=== "C++"

    ``` c++
    #include <iostream>

    int main(void) {
      std::cout << "Hello world!" << std::endl;
      return 0;
    }
    ```

他们呈现的效果:

C
#include <stdio.h>

int main(void) {
  printf("Hello world!\n");
  return 0;
}
C++
#include <iostream>

int main(void) {
  std::cout << "Hello world!" << std::endl;
  return 0;
}

脚注(Footnotes)

脚注和类似标注和注解的结合体,就个人而言它完全可以被注解替代。

将下面添加到 mkdocs.yml 来开启脚注:

YAML
markdown_extensions:
  - footnotes

它是配套使用的,需要标记的地方 [^<num>],之后在任意位置添加 [^1]: content

Note

比较特殊的就是无论在哪里定义 [^1]: content 他们都会展示在文档的底部。

图片(images)

主要是提供了一些参数来控制图片的对齐和展示大小。

将下面添加到 mkdocs.yml 来开启高级图片支持:

YAML
markdown_extensions:
  - attr_list
  - md_in_html

可以在标准的图片标记后面添加 { align=left }等定义:

Markdown
![Image title](https://dummyimage.com/600x400/eee/aaa){ align=left }

![Image title](https://dummyimage.com/600x400/){ width="300" }

工具提示(Tooltips)

对于技术文档很多专有名词是首字母缩写词,这可能需要额外的解释。而工具提示就是干这个使用的。他提供来鼠标悬停来显示词语解释。

将下面添加到 mkdocs.yml 来开启工具提示:

YAML
markdown_extensions:
  - abbr
  - attr_list
  - pymdownx.snippets

这里主要讲解对缩略文本的提示:

Markdown
The HTML specification is maintained by the W3C.

*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web Consortium

最终渲染效果如下:

The HTML specification is maintained by the W3C.

甚至允许定义一个专门的词汇表:

Markdown
*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web Consortium
YAML
markdown_extensions:
  - pymdownx.snippets:
      auto_append:
        - includes/abbreviations.md

Tip

为了mkdocs serve能够自动渲染,需要将词汇表所在的目录添加到 watch 中:

YAML
watch:
  - includes
includes 一定要和 docs 同目录,即在项目根目录下

列表

MkDocs 使用 Python-Markdown 来解析 Markdown 文档,它只识别 4 空格作为缩进。而大多数 format 都使用 2 空格进行缩进,因此:

Markdown
- title
  - t1
  - t2

<!-- 被识别为 -->

- title
- t1
- t2

如果不希望这样就需要安装mdx_truly_sane_lists插件,并配置:

YAML
markdown_extensions:
  - mdx_truly_sane_lists

部署

可以使用 mkdocs build 来构建 site 手动放置到对应 Web 服务器上部署。如果是个人使用可以使用 GitHub/GitLab/Gitee Pages 来实现部署。

GitLab Pages

我们只需要在 GitLab 上托管我们的代码,然后在存储库的根目录创建名为 .gitlab-ci.yml 的 GitLab CI 任务来实现自动发布:

.gitlab-ci.yml
pages:
  stage: deploy
  image: python:latest
  script:
    - pip install mkdocs-material
    - mkdocs build --site-dir public
  artifacts:
    paths:
      - public
  rules:
    - if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"

现在只要我们提交到默认分支, GitLab CI 会自动运行上面的命令来构建和部署静态站点。之后我们只需要 <username>.gitlab.io/<repository> 就可以浏览了。