如何在节点中使用 rst?例如我想输出包含的文件about.rst
class Foo(Directive):
def run(self):
return [
nodes.Text("**adad**"), # <-- Must be a bold text
nodes.Text(".. include:: about.rst"), # <-- Must include file
]
如何在节点中使用 rst?例如我想输出包含的文件about.rst
class Foo(Directive):
def run(self):
return [
nodes.Text("**adad**"), # <-- Must be a bold text
nodes.Text(".. include:: about.rst"), # <-- Must include file
]
您可以构造一个ViewList
原始的第一个数据(每个条目一行),让 Sphinx 解析该内容,然后返回 Sphinx 给您的节点。以下对我有用:
from docutils import nodes
from docutils.statemachine import ViewList
from sphinx.util.compat import Directive
from sphinx.util.nodes import nested_parse_with_titles
class Foo(Directive):
def run(self):
rst = ViewList()
# Add the content one line at a time.
# Second argument is the filename to report in any warnings
# or errors, third argument is the line number.
rst.append("**adad**", "fakefile.rst", 10)
rst.append("", "fakefile.rst", 11)
rst.append(".. include:: about.rst", "fakefile.rst", 12)
# Create a node.
node = nodes.section()
node.document = self.state.document
# Parse the rst.
nested_parse_with_titles(self.state, rst, node)
# And return the result.
return node.children
def setup(app):
app.add_directive('foo', Foo)
我必须为一个项目做类似的事情——代替任何(很容易找到的)相关文档,我使用内置 autodoc 扩展的源作为指南。
添加内容以 rst 语法格式化的文本节点无济于事。您需要创建第一个节点对象来构建所需的第一个元素树。此外,由于您尝试在示例中包含另一个 rst 文件,因此您需要使用嵌套解析,因为实际内容事先不知道并且无法硬编码。
在run()
rst 指令类的self.state.nested_parse()
方法中,可以调用方法。它的最初目的是像这样解析指令的内容:
# parse text content of this directive
# into anonymous node element (can't be used directly in the tree)
node = nodes.Element()
self.state.nested_parse(self.content, self.content_offset, node)
在您的情况下,您可以尝试打开abour.rst
文件,解析它并将解析的节点树添加到结果节点列表中,或者您可以尝试使用包含指令对字符串常量运行嵌套解析。