如何在节点中为指令添加 rst 格式? [英] How to add rst format in nodes for directive?

查看:47
本文介绍了如何在节点中为指令添加 rst 格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在节点中使用 rst?例如我想输出包含文件 about.rst

How I can use rst in nodes? For example I want to output icluded file 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 数据的 ViewList(每个条目一行),让 Sphinx 解析该内容,然后返回 Sphinx 给你的节点.以下对我有用:

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)

我不得不为一个项目做类似的事情——代替任何(很容易找到的)相关文档,我使用了 内置 autodoc 扩展源 作为指南.

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.

这篇关于如何在节点中为指令添加 rst 格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆