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

2024-05-19 12:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

交叉引用自定义指令生成的节时遇到问题

以下是指令:

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)

下面是它的使用方法:

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

.. mytest:: section1

Section 1 content.


.. _section2:

section2
========

Section 2 content.

现在,以下仅适用于section2

Here are links to :ref:`section1` and :ref:`section2`.

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

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

我怎样才能做到这一点


Tags: fromimporttargetmy指令argsectionrst
1条回答
网友
1楼 · 发布于 2024-05-19 12:03:19

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

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

  • 加工零件的reference label.. _section2:)直接位于section titlesection2带装饰下划线)之前。它提供了一个可以通过interpreted text role:ref:`section2`)链接到的目标。这是斯芬克斯的标准样板
  • 不起作用的部分有您的自定义指令(.. mytest::)及其单个必需参数(section1),并且没有内容块(指令后面没有缩进文本)
  • 行“Section 1 content.”是一个独立的段落

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


编辑

:ref:角色用于任意位置(“标签”,不管是什么意思) 但您也可以通过:any:once it is registered交叉引用自定义对象:

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

    app.add_object_type(
        directivename='mytest',
        rolename='banana',
    )

然后休息内容:

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

Or also works via the rolename :banana:`section1`.

Many would agree所有这些功能都没有很好的文档记录

相关问题 更多 >

    热门问题