问题
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