Sphinx:如何交叉引用自定义指令生成的目标

abe*_*bey 7 python cross-reference docutils python-sphinx

我在交叉引用自定义指令生成的部分时遇到问题。

这是指令:

from docutils import nodes
from docutils.parsers import rst


class TestDirective(rst.Directive):

    has_content = False
    required_arguments = 1
    option_spec = {}

    def run(self):
        my_arg = self.arguments[0]

        target_node = nodes.target('', '', refid=nodes.make_id(my_arg))
        section = nodes.section(
            '',
            nodes.title(text=my_arg),
            ids=[nodes.make_id(my_arg)],
            names=[nodes.fully_normalize_name(my_arg)])

        return [target_node, section]


def setup(app):
   app.add_directive('mytest', TestDirective)
Run Code Online (Sandbox Code Playgroud)

这是它的使用方法:

=============
Test document
=============

.. mytest:: section1

Section 1 content.


.. _section2:

section2
========

Section 2 content.
Run Code Online (Sandbox Code Playgroud)

现在,以下仅适用于section2

Here are links to :ref:`section1` and :ref:`section2`.
Run Code Online (Sandbox Code Playgroud)

该链接仅正确生成section2,我收到以下错误:

test.rst:19: WARNING: undefined label: section1 (if the link has no caption the
label must precede a section header)
Run Code Online (Sandbox Code Playgroud)

我怎样才能使这项工作?

Apr*_*pos 1

您似乎混淆了引用标签与指令的功能。

为了使术语清晰,请在标记中:

  • 有效的部分在部分标题(带有装饰下划线的“ ”)之前有一个参考标签( ) 。这提供了一个可以通过解释文本角色链接到的目标( )。这是常规的 Sphinx 样板。.. _section2:section2:ref:`section2`
  • 不起作用的部分是您的自定义指令 ( .. mytest::) 及其单个必需参数 ( section1) 并且没有内容块(指令后面没有缩进文本)。
  • “ ”行Section 1 content.是一个独立的段落。

也许您想要一个自定义解释文本角色来提供特殊功能、roles.XRefRole子类或autosectionlabel 扩展


编辑

该角色适用于任意位置(“标签”,无论这意味着什么),但您也可以在注册后:ref:通过交叉引用自定义对象::any:

def setup(app):
    app.add_directive('mytest', TestDirective)

    app.add_object_type(
        directivename='mytest',
        rolename='banana',
    )
Run Code Online (Sandbox Code Playgroud)

然后ReST内容:

See :any:`section1` which is a TestDirective.

Or also works via the rolename :banana:`section1`.
Run Code Online (Sandbox Code Playgroud)

许多人都会同意,所有这些功能的文档都很少。