2

我正在 Sphinx 中编写自定义角色/指令,我需要插入一个节点,在该节点中我将文本字符串解释为 reStructuredText。有没有办法做到这一点?

我找到了这个来源http://agateau.com/2015/docutils-snippets,它说明了如何使用docutils.nodes类以编程方式构建文档树片段,例如

class BulletList(Directive):
    def run(self):
        fruits = ['Apples', 'Oranges', 'Bananas']

        lst = nodes.bullet_list()
        for fruit in fruits:
            item = nodes.list_item()
            lst += item
            item += nodes.paragraph(text=fruit)

        return [lst]

我想做的是

:myrole:`this is *really* cool|trade|`

通过在 conf.py 中执行此操作:

def myrole(name, rawtext, text, lineno, inliner, options={}, content=[]):
    # somehow convert the "text" parameter into docutils nodes
    # by interpreting it as RST
    nodes = ???? what goes here ???
    return nodes, []

def setup(app):
    app.add_role('myrole', myrole)
4

1 回答 1

1

您想self.state.nested_parse在指令的run()方法中使用:

许多指令将包含更多必须解析的标记。为此,请使用 Directive.run() 方法中的以下 API 之一:

self.state.nested_parse

sphinx.util.nodes.nested_parse_with_titles()– 这允许在解析的内容中使用标题。

两个 API 都将内容解析到给定的节点中。它们是这样使用的:

node = docutils.nodes.paragraph()
# either
nested_parse_with_titles(self.state, self.result, node)
# or
self.state.nested_parse(self.result, 0, node)

这个关于使用 a 创建输入的问题ViewList()也可能是相关的。

我不确定您是否可以在角色中使用它。显然,您将无法使用该self.变体,因为角色在任何情况下都是函数。

于 2019-09-11T23:56:42.347 回答