当使用带有Sphinx 的reStructuredText 时,请使用the ref role 交叉引用文档中的其他位置:
:ref:`link text <link-target>`
如果引用的对象定义了标题或标题,则自定义链接文本是可选的,例如文档、章节、图形等。然后目标的标题将用作链接文本,但必须省略尖括号::ref:`link-target` 。引用段落或图像时,链接文本是强制性的,因为它们没有与之关联的标题/说明。
链接目标必须在文档中的某个地方定义,可能在其他文档中,即.rst文件。对于部分,扩展名Autosectionlabel 会自动执行此操作,然后部分的标题成为目标,因此也链接文本。在所有其他情况下,internal hyperlink targets 必须手动声明,例如:
.. _paragraph-to-be-linked-to:
This paragraph will be referenced from elsewhere in the documentation
with :ref:`that paragraph <paragraph-to-be-linked-to>`.
注意目标定义中的前导下划线。它can be thought of as a right-pointing arrow,这里指向内部,指向链接目标。我们还可以使用inline internal targets 链接到(长)段落内的特定位置:
We want to point to _`this position` inside the paragraph
with :ref:`that paragraph <this position>` from elsewhere.
单独使用带有Docutils 的reStructuredText 时,ref 角色不可用,因为它是 Sphinx 添加的语法扩展。相反,我们需要以下语法来创建hyperlinks:
`link text <link-target_>`_
注意两个尾随下划线,一个在链接目标之后,另一个在完整超链接之后。这里假想的箭头指向外面。
Docutils 只处理standalone files。 Sphinx 使用它作为后端来解析单个 reStructuredText 源文件。因此,在 Sphinx 文档中,后一种语法仅适用于同一文档中的内部链接,但不适用于跨文档,即在一个 .rst 文件中定义的超链接引用另一个文件中的目标。
Sphinx 提供的the any role 代替ref 角色可能更方便。它还将查找由扩展自动创建的链接目标,例如使用Autodoc 记录的源代码对象。当在conf.py 中声明为default role 和default_role = 'any' 时,我们可以编写`link text <link-target>` 甚至只是`link-target` 来创建内部超链接。除了没有尾随下划线之外,前者看起来很像 Docutils 识别的单文档 reStructuredText 的语法,但由 Sphinx 以跨文档方式处理。