How to create referenceable label node above section in sphinx

大兔子大兔子 提交于 2021-02-08 09:17:37

问题


I am creating a custom directive in sphinx. This directive lists all possible objects (each one in separate section).

Now I would like those objects to be referenceable from other parts (files) of documentation.

I was trying to do something very simple like:

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]

but it doesn't allow me to reference to this section neither by :ref:object-unique-id1, :ref:object-unique-id2 nor :ref:abc.

So my question is: How to create node that can be referenced ?


回答1:


Adding a target immediately before the section appears to work. Something like:

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]

Note the call to self.state.add_target.

Somewhere later in the build the target is magically created and should be able to refer to your section with

:ref:`abc`

anywhere in your project.



来源:https://stackoverflow.com/questions/25830915/how-to-create-referenceable-label-node-above-section-in-sphinx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!