Skip to main content
 首页 » 编程设计

python之如何在 sphinx 的上面部分创建可引用的标签节点

2025年05月04日10wuhuacong

我正在 sphinx 中创建自定义指令。 该指令列出了所有可能的对象(每个对象都在单独的部分中)。

现在我希望可以从文档的其他部分(文件)引用这些对象。

我正在尝试做一些非常简单的事情,例如:

class MyDirective(Directive): 
    def run(self, obj): 
        id1 = 'object-unique-id1' 
        id2 = 'object-unique-id2' 
        label = nodes.label('abc1', refid=id1) 
        section = nodes.section(ids=[id2]) 
        section += nodes.title(text='abc') 
        section += label 
        return [section] 

但它不允许我通过 :ref:object-unique-id1, :ref:object-unique-id2 或 :ref:object-unique-id2 引用此部分:引用:abc.

所以我的问题是:如何创建可以引用的节点?

请您参考如下方法:

在该部分似乎起作用之前立即添加一个目标。像这样的东西:

class MyDirective(Directive): 
    def run(self, obj): 
        titleTxt = 'abc' 
        lineno = self.state_machine.abs_line_number() 
        target = nodes.target() 
        section = nodes.section() 
 
        # titleTxt appears to need to be same as the section's title text 
        self.state.add_target(titleTxt, '', target, lineno)  
        section += nodes.title(titleTxt, '') 
 
        return [target, section] 

注意对 self.state.add_target 的调用。

在构建的后期某个地方神奇地创建了目标,并且应该能够通过

引用您的部分
:ref:`abc` 

项目中的任何位置。