# 文档编写指南
```{contents}
---
local:
depth: 1
---
```
(writing_style_guide)=
## 写作风格指南
为保证语气与用词一致,编写 Wagtail 文档时请遵循[谷歌开发者文档风格指南](https://developers.google.com/style)。
## 格式建议
Wagtail 的文档混用 [Markdown(配合 MyST)](inv:myst#syntax/core) 与 [reStructuredText](inv:sphinx#rst-primer)。我们鼓励优先用 Markdown 写文档,只在有充分理由时才使用更高级的 reStructuredText 格式。Python 代码中的 docstring 必须用 reStructuredText 编写,因为目前尚不支持在 docstring 中使用 Markdown。
以下是编写 Wagtail 文档时我们鼓励使用的格式。
### 段落
一切从这里开始。
保持句子简短,长度有变化。
用空行分隔文本以创建新段落。
### 拉丁语短语与缩写
尽量避免使用拉丁语短语(例如 `ergo` 或 `de facto`)和缩写(例如 `i.e.` 或 `e.g.`),改用常见的英文短语。或者,找一种更简单的方式把概念或想法传达给读者。例外是 `etc.`,在篇幅受限时可以使用。
示例:
| 不要使用 | 改用 |
| -------------- | -------------------- |
| e.g. | 例如、比如 |
| i.e. | 也就是说 |
| viz. | 即 |
| ergo | 因此 |
### 标题层级
用标题层级来划分章节,让用户可以直接链接到某个具体章节。文档以 `# h1` 开始,接着用 `## h2` 和更细的子章节,不要跳过层级。
```md
# Heading level 1
## Heading level 2
### Heading level 3
```
### 列表
无序列表用项目符号,有序列表用数字。项目符号优先用短横线 `-`。嵌套时用 4 个空格缩进。
```md
- Bullet 1
- Bullet 2
- Nested bullet 2
- Bullet 3
1. Numbered list 1
2. Numbered list 2
3. Numbered list 3
```
渲染结果
- Bullet 1
- Bullet 2
- Nested bullet 2
- Bullet 3
1. Numbered list 1
2. Numbered list 2
3. Numbered list 3
### 行内样式
**粗体**和*斜体*要少用,相关时使用行内 `code`。
```md
Use **bold** and _italic_ sparingly and inline `code` when relevant.
```
请记住,在 reStructuredText 中,斜体用 `*` 书写,行内代码必须用双反引号书写,例如 ` ``code`` `。
```rst
Use **bold** and *italic* sparingly and inline ``code`` when relevant.
```
### 代码块
务必写上正确的语言代码以便语法高亮,并按我们的编码规范格式化你的代码。常用的有:`python`、`css`、`html`、`html+django`、`javascript`、`sh`。
````md
```python
INSTALLED_APPS = [
...
"wagtail",
...
]
```
````
渲染结果
```python
INSTALLED_APPS = [
...
"wagtail",
...
]
```
#### 使用控制台(终端)代码块时
```{note}
不需要 `$` 或 `>` 提示符,这会让人更难复制粘贴这些行,而且很难在每一个代码片段中都稳定地加上。
```
使用 `sh`,因为 MyST 的解析器对它支持更好,能高亮注释与代码语法,并且与 GitHub 和 VSCode 更兼容。
````md
```sh
# some comment
some command
```
````
渲染结果
```sh
# some comment
some command
```
只有在明确要列出 Windows 命令及其对应的 bash 等价命令时,才使用 `doscon`(DOS 控制台)。
````md
```doscon
# some comment
some command
```
````
渲染结果
```doscon
# some comment
some command
```
#### 包含三重反引号的代码块
你可以用三个或更多反引号来创建代码块。如果需要在代码块中包含三重反引号,可以用不同数量的反引号包裹该代码块。这在需要演示 Markdown 代码块时很有用,例如上面的示例。
`````md
````md
```python
print("Hello, world!")
```
````
`````
渲染结果
````md
```python
print("Hello, world!")
```
````
### 链接
链接是文档的基础。用内部链接把内容与其它文档关联起来,按需使用外部链接。为链接挑选相关的文本,让读者知道自己会落到哪里。
不要让外部链接藏住对读者至关重要的上下文。应当把核心信息写在页面上,用链接提供补充上下文。
```md
An [external link](https://www.example.com).
An [internal link to another document](/reference/contrib/legacy_richtext).
An auto generated link label to a page [](/getting_started/tutorial).
A [link to a target](register_reports_menu_item).
Do not use [click here](https://www.example.com) as the link's text, use a more descriptive label.
Do not rely on links for critical context, like [why it is important](https://www.example.com).
```
渲染结果
An [external link](https://www.example.com).
An [internal link to another document](/reference/contrib/legacy_richtext).
An auto generated link label to a page [](/getting_started/tutorial).
A [link to a target](register_reports_menu_item).
Do not use [click here](https://www.example.com) as the link's text, use a more descriptive label.
Do not rely on links for critical context, like [why it is important](https://www.example.com).
#### 锚点链接
锚点链接指向页面上的某个具体目标。它们依赖页面上已创建该目标。每个目标必须有唯一的名称,并应使用 `lower_snake_case` 格式。目标可以如下添加:
```md
(my_awesome_section)=
##### Some awesome section title
...
```
可以用 Markdown 链接语法链接到该目标,并可选地给出标签,如下所示:
```md
- Auto generated label (preferred) [](my_awesome_section)
- [label for section](my_awesome_section)
```
渲染结果:
(my_awesome_section)=
##### 某个很棒的章节标题
...
- Auto generated label (preferred) [](my_awesome_section)
- [label for section](my_awesome_section)
关于其它链接与创建引用的方式,可以阅读 MyST-Parser 文档中 [](inv:myst#syntax/cross-referencing) 一节。
#### Intersphinx 链接(外部文档)
由于存在大量指向外部文档(尤其是 Django)的链接,我们通过 intersphinx 引用加入了集成。它在 `docs/conf.py` 文件中通过 [](inv:sphinx:std:confval#intersphinx_mapping) 配置。这让你可以链接到某个项目文档的具体章节,并在目标不再可用时收到警告。
Markdown 示例:
```md
You can select widgets from [Django's form widgets](inv:django#ref/forms/widgets).
```
reStructuredText 示例:
```rst
You can select widgets from :doc:`Django form widget `.
```
Markdown 中 Sphinx 链接的格式是 `inv:key:domain:type#name`。其中 `key`、`domain`、`type` 是可选的,但建议写出来,以免在存在多个同名 `name` 目标时产生歧义。
如果 `name` 中含有空格,需要用尖括号 `<>` 把整个链接包起来。
```md
See Django's docs on []().
```
渲染结果
See Django's docs on []().
##### 找到正确的 intersphinx 目标
你想链接到的某个具体锚点,其 intersphinx 目标可能并不明显。你可以使用 MyST-Parser 的 `myst-inv` 命令行工具,并把输出保存为 JSON 或 YAML 文件,以便直观查看可用的目标。
```sh
myst-inv https://docs.djangoproject.com/en/stable/_objects/ --format=json > django-inv.json
```
借助 `myst-inv` 的输出,你可以顺着 `objects` 键下的树状结构来构建链接目标。VSCode 之类的一些文本编辑器在你浏览该文件时会显示指向目标的面包屑路径。
也有其它工具可帮助你浏览 Sphinx 的清单,例如 [sphobjinv](https://github.com/bskinn/sphobjinv) 和 Sphinx 内置的 `sphinx.ext.intersphinx` 扩展。
```sh
sphobjinv suggest "https://docs.djangoproject.com/en/stable/_objects/" 'template fragment caching' -su
python -m sphinx.ext.intersphinx https://docs.djangoproject.com/en/stable/_objects/
```
某些情况下,文档中可能存在更具体的目标。不过你可能需要查看该页面的源代码才能找到它。
例如,上面提到的那节 Django 文档也可以通过类型 `templatetag` 和名称 `cache` 来链接。
```md
See Django's docs on the [](inv:django:std:templatetag#cache) tag.
```
渲染结果
See Django's docs on the [](inv:django:std:templatetag#cache) tag.
注意,虽然该链接会把你带到同一节内容,但 URL 哈希和默认文本会不同。如果你使用了自定义文本,这对读者可能没有区别。不过,它们在语义上并不相同。
当你是在一般性的文档上下文中做链接时(例如一篇讲如何做缓存的指南),使用第一种做法(`label` 类型)。当你是在写代码的上下文中做链接时(例如 `{% cache %}` 模板标签的用法),使用第二种做法(`templatetag` 类型)。编写 docstring 时通常更推荐第二种做法。
#### 绝对链接
有时,外部文档的某些章节完全没有附上 Sphinx 目标。在链接到这类章节之前,先考虑链接到该章节之前最近的那个目标。如果有可用的目标距离足够近,点到链接时你想要的章节就能立即看到,那就用它。否则,可以写成完整 URL。记得使用 `stable` 版本的 URL,而不要用某个具体版本。
使用完整 URL 而非 intersphinx 链接的一个常见例子,是链接到 Django 发布说明中的章节。
```md
`DeleteView` has been updated to align with [Django 4.0's `DeleteView` implementation](https://docs.djangoproject.com/en/stable/releases/4.0/#deleteview-changes).
```
渲染结果
`DeleteView` has been updated to align with [Django 4.0's `DeleteView` implementation](https://docs.djangoproject.com/en/stable/releases/4.0/#deleteview-changes).
对于没有 intersphinx 映射的外部网站链接,始终使用 `https://` 协议。
对于一次性指向外部文档的链接,也更推荐使用绝对链接,即使该网站有 Sphinx 对象清单。一旦指向同一项目的链接达到三个或更多,就可以考虑在可能的情况下添加 intersphinx 映射。
#### 代码引用
链接到代码引用时,可以使用 Sphinx 的[引用角色](inv:sphinx#usage/restructuredtext/roles)。
Markdown 示例:
```md
The {class}`~django.db.models.JSONField` class lives in the {mod}`django.db.models.fields.json` module,
but it can be imported from the {mod}`models ` module directly.
For more info, see {ref}`querying-jsonfield`.
```
reStructuredText 示例:
```rst
The :class:`~django.db.models.JSONField` class lives in the :mod:`django.db.models.fields.json` module,
but it can be imported from the :mod:`models ` module directly.
For more info, see :ref:`querying-jsonfield`.
```
渲染结果
The {class}`~django.db.models.JSONField` class lives in the {mod}`django.db.models.fields.json` module,
but it can be imported from the {mod}`models ` module directly.
For more info, see {ref}`querying-jsonfield`.
在点分路径前加上 `~` 会把链接文本缩短为最后一部分(即对象名)。当完整路径已经在正文中出现时,这很有用。你也可以用 [`module`](inv:sphinx:rst:directive#py:module) 或 [`currentmodule`](inv:sphinx:rst:directive#py:currentmodule) 指令设定文档当前的作用域,从而避免为每个对象都写出完整路径。
````md
```{currentmodule} wagtail.admin.viewsets.model
```
The {class}`ModelViewSet` class extends the {class}`~wagtail.admin.viewsets.base.ViewSet` class.
````
渲染结果
```{currentmodule} wagtail.admin.viewsets.model
```
The {class}`ModelViewSet` class extends the {class}`~wagtail.admin.viewsets.base.ViewSet` class.
```{currentmodule} None
```
引用角色还可以定义自身的渲染方式。在上面的示例中,[`class`](inv:sphinx:rst:role#py:class) 和 [`mod`](inv:sphinx:rst:role#py:mod) 角色会被渲染成带链接的行内代码,而 [`ref`](inv:sphinx:rst:role#ref) 角色会被渲染成普通链接。
这些特性使引用角色在编写参考类文档和 docstring 时特别有用。
除了使用引用角色,你也可以使用链接语法。与引用角色不同,链接语法要求给出对象的完整路径,同时允许你自定义链接标签。当你想避开引用角色的默认渲染方式时(例如想在链接标签中混用行内代码和普通文本),这会很有用。
```md
For more details on how to query the [`JSONField` model field](django.db.models.JSONField),
see [the section about querying `JSONField`](inv:django#querying-jsonfield).
```
渲染结果
For more details on how to query the [`JSONField` model field](django.db.models.JSONField),
see [the section about querying `JSONField`](inv:django#querying-jsonfield).
### 提示与警告块
少用提示和警告块,只在需要时用它引起读者注意。它们可以用来提供补充上下文,或警告潜在问题。
```{note}
Notes can provide complementary information.
```
```{warning}
Warnings can be scary.
```
渲染结果
```{note}
Notes can provide complementary information.
```
```{warning}
Warnings can be scary.
```
这些提示块不支持标题,因此注意不要给它加标题,标题只会被移到提示块的正文里。
```{note} Title's here will not work correctly
Notes can provide complementary information.
```
### 图片
随着文档演进,图片很难维护,但有时仍然值得。添加图片时请遵循以下准则:
- 所有图片都应有有意义的[替代文本](https://axesslab.com/alt-texts/),除非它们只是装饰性的。
- 图片按原样提供 —— 选择正确的格式,并对所有图片做无损压缩。
- 图片文件使用绝对路径,以便更好地移植。
```md

```
渲染结果

### Docstring 与 API 参考(autodoc)
借助 [autodoc](inv:sphinx#ext-autodoc) 功能,Sphinx 支持在 Python docstring 中编写文档,以便后续整合到项目文档页面中。这是一个非常强大的特性,我们高度推荐用它来为 Wagtail 的 API 编写文档。
模块、类和函数都可以用 docstring 写文档。类和实例属性可以用 docstring(三重引号 `"""`)或文档注释(井号冒号 `#:`)来写。推荐使用 docstring,因为它们与代码编辑器的集成更好。Python 代码中的 docstring 必须用 reStructuredText 语法编写。
```py
SLUG_REGEX = r"^[-a-zA-Z0-9_]+$"
"""模块级变量 ``SLUG_REGEX`` 的 docstring。"""
class Foo:
"""类 ``Foo`` 的 docstring。"""
bar = 1
"""类属性 ``Foo.bar`` 的 docstring。"""
#: 类属性 ``Foo.baz`` 的文档注释。
#: 它可以有多行,每行都必须以 ``#:`` 开头。
#: 注意它写在属性之前。
#: 虽然 Sphinx 支持这样做,但并不推荐。
baz = 2
def __init__(self):
self.spam = 4
"""实例属性 ``spam`` 的 docstring。"""
```
autodoc 扩展提供了许多用于记录 Python 代码的指令,例如 [`autoclass`](inv:sphinx#autoclass)、[`autofunction`](inv:sphinx#autofunction)、[`automodule`](inv:sphinx#automodule),以及用于定制输出的各种选项。在 Markdown 文件中,这些指令需要包在 `eval-rst` 指令里。与 docstring 一样,`eval-rst` 块内的所有内容都必须用 reStructuredText 语法编写。
你可以混用自动与非自动文档。例如,你可以用 [`module`](inv:sphinx#py:module) 代替 `automodule`,在 `eval-rst` 块中写模块的文档,但仍用 `autoclass` 和 `autofunction` 处理类与函数。推荐使用自动文档,因为它能降低代码与文档之间不一致的风险,并与代码编辑器集成更好。
```{eval-rst}
.. module:: wagtail.coreutils
Wagtail's core utilities.
.. autofunction:: cautious_slugify
:no-index:
```
渲染结果
```{eval-rst}
.. module:: wagtail.coreutils
:no-index:
Wagtail's core utilities.
.. autofunction:: cautious_slugify
:no-index:
```
关于可用指令与选项的更多细节,请参阅 Sphinx 文档中的 [](inv:sphinx#autodoc-directives) 和 [](inv:sphinx#usage/domains/python)。
### 表格
只在需要时使用表格,使用 [GitHub Flavored Markdown 表格语法](https://github.github.com/gfm/#tables-extension-)。
```md
| Browser | Device/OS |
| ------------- | --------- |
| Stock browser | Android |
| IE | Desktop |
| Safari | Windows |
```
渲染结果
| Browser | Device/OS |
| ------------- | --------- |
| Stock browser | Android |
| IE | Desktop |
| Safari | Windows |
### 目录
可以用 [`toctree` 和 `contents` 指令](inv:myst#organising-content)来渲染目录。
```{toctree}
---
maxdepth: 2
titlesonly:
---
getting_started/index
topics/index
```
```{contents}
---
local:
depth: 1
---
```
### 版本新增、变更与弃用
Sphinx 提供发布元数据指令,以一致的方式呈现关于新增或更新特性的信息。
```{versionadded} 2.15
The `WAGTAIL_NEW_SETTING` setting was added.
```
```{versionchanged} 2.15
The `WAGTAIL_OLD_SETTING` setting was deprecated.
```
渲染结果
```{versionadded} 2.15
The `WAGTAIL_NEW_SETTING` setting was added.
```
```{versionchanged} 2.15
The `WAGTAIL_OLD_SETTING` setting was deprecated.
```
这些指令通常会在添加两个发布版本后被移除,因此只应用于短时效的信息,例如「`WAGTAILIMAGES_CACHE_DURATION` 设置已添加」。关于该特性的详细文档应写在正文中,即指令之外。
### 渐进式展开
我们可以用 HTML 的 `` 元素在文档中添加补充信息。这依赖 HTML 语法,而 HTML 语法很难稳定地编写,因此这类格式应尽量少用。
```html
Supplementary information
This will be visible when expanding the content.
```
示例:
补充信息
展开内容时才会显示这段说明。
## 应避免的格式
文档中有一些格式在技术上是支持的,但除非确有明确必要,我们建议避免使用。
### 提示块
我们只使用 `{note}` 和 `{warning}` 提示块。避免使用 `{admonition}`、`{important}`、`{topic}` 和 `{tip}`。如果你发现其中某一个,请把它替换为 `{note}`。
### 术语表
Sphinx 的术语表(`.. glossary::`)会生成定义列表。请改用普通的项目符号列表或数字列表,或者用带标题的章节,或者用表格。
### 注释
提交到仓库的文档中避免保留源码注释。
### Figure
reStructuredText 的图(`.. figure::`)相比普通图片只有很小的改进。如果你的图需要题注,请在图片下另起一个斜体段落写题注。
### 其它 reStructuredText 语法与 Sphinx 指令
我们总体上希望优先用 Markdown 而不是 reStructuredText,使新人为 Wagtail 贡献文档尽可能简单。始终优先选择 Markdown,除非文档的格式高度依赖 reStructuredText 语法。
如果你想使用某个特定的 Sphinx 指令,请与核心贡献者沟通,确认其使用是否确有必要,并在本页记录其预期用法。
### reStructuredText 中的 Markdown
反过来,在需要 reStructuredText 的地方不要使用 Markdown 语法。一个常见错误是在 Python 代码的 docstring 和 `eval-rst` 指令内部写 Markdown 风格的行内 `` `code` ``(单反引号)。这不被支持,也不会正确渲染。
### 任意 HTML
虽然我们的文档工具对嵌入任意 HTML 有一定支持,但这样做并不受欢迎。只有在确有需要、且该格式不太可能需要更新时才这样做。
(documentation_code_example_considerations)=
## 代码示例的考量
在包含代码示例时(尤其是 JavaScript 或内嵌 HTML),务必遵循安全与无障碍方面的最佳实践,并采用让示例更易理解的做法。
这些不是硬性规定,而是编写示例代码时应做的考量。
### 引用示例文件名
在代码片段开头,在顶部引用一个示例文件名会很有帮助。例如:`# wagtail_hooks.py` 或 `// js/my-custom.js`。
### 符合 CSP(内容安全策略)
在添加来自外部来源的 JavaScript 或自定义脚本时,确保符合 CSP,以防止跨站脚本(XSS)等安全漏洞。
尽量避开 `mark_safe`,改用 `format_html`,并使用加载外部文件的示例来安全管理脚本,而不是内联 `