【问题标题】:How to programmatically interpret reStructuredText into docutil nodes?如何以编程方式将 reStructuredText 解释为 docutil 节点?
【发布时间】:2016-09-01 21:52:29
【问题描述】:

我正在 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)

【问题讨论】:

    标签: python-sphinx restructuredtext docutils


    【解决方案1】:

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

    许多指令将包含更多必须解析的标记。为此,请使用 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)
    

    This question about creating input using a ViewList() 也可能是相关的。

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

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2017-11-19
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2022-08-12
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多