2015-12-18 31 views
3

我如何在節點中使用rst?比如我要輸出icluded文件about.rst如何在節點中添加rst格式的指令?

class Foo(Directive): 

    def run(self): 
     return [ 
      nodes.Text("**adad**"), # <-- Must be a bold text 
      nodes.Text(".. include:: about.rst"), # <-- Must include file 
     ] 

回答

2

您可以構建原始rst數據的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) 

我不得不做的一個項目類似的東西---代替我用source of the inbuilt autodoc extension爲導向的任何(很容易找到)相關文件。

1

添加文本節點與第一個語法不會幫助格式的內容。您需要創建第一個節點對象來構建所需的第一個元素樹。此外,由於您嘗試在示例中包含另一個第一個文件,因此您需要使用嵌套解析,因爲實際內容未提前知道且無法進行硬編碼。

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文件,分析它,並添加 解析節點樹到結果節點列表或者你可以嘗試用include指令運行嵌套的 解析字符串常量。

相關問題