How to add rst format in nodes for directive?

纵饮孤独 提交于 2019-12-05 12:09:59

You can construct a ViewList of your raw rst data (one line per entry), get Sphinx to parse that content, and then return the nodes Sphinx gives you. The following worked for me:

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)

I had to do something similar for a project --- in lieu of any (easily found) relevant documentation I used the source of the inbuilt autodoc extension as a guide.

Adding text nodes with content formatted with rst syntax wouldn't help. You need to create rst node objects to build required rst element tree. Moreover since you try to include another rst file in the example, you would need to use nested parsing as the actual content is not known in advance and can't be hardcoded.

In run() method of rst directive class, self.state.nested_parse() method can be called. It's original purpose is to parse content of the directive like this:

# 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)

In your case you would either try to open abour.rst file, parse it and add parsed node tree into the result node list or you can just try to run nested parse on string constant with include directive.

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