【问题标题】:How can I use an existing Directive within a custom python-sphinx Directive/extension?如何在自定义 python-sphinx 指令/扩展中使用现有指令?
【发布时间】:2020-07-19 12:37:24
【问题描述】:

我想创建一个自定义 Directive,在其实现中使用现有指令(本示例中为 code-block)。

reStructuredText 中的手动等效项是:

.. mydirective:: py

   .. code-block: py
        
      print("Hello world")     

但是,我希望在 my-directive 的定义中创建 code-block。我找到了一个为现有指令(如下)硬编码适当reStructuredText 的示例,但这取决于使用rST 的解析器。

class MyDirective(Directive):
    has_content = True

    def run(self):
        # Do custom stuff...

        # Use code-block Directive
        new_content = [
            '.. tab:: {}'.format(json.dumps(tab_args)),
            '   {}'.format(tab_name),
            '',
            '   .. code-block:: {}'.format(lang),
        ]

        if 'linenos' in self.options:
            new_content.append('      :linenos:')

        new_content.append('')

        for idx, line in enumerate(new_content):
            self.content.data.insert(idx, line)
            self.content.items.insert(idx, (None, idx))

        node = nodes.container()
        self.state.nested_parse(self.content, self.content_offset, node)
        return node.children

如何以独立于解析器的方式实现这一点?

【问题讨论】:

    标签: python python-sphinx docutils


    【解决方案1】:

    最后,我的解决方案是:

    from sphinx.directives.code import CodeBlock
    
    
    class CodeTabDirective(CodeBlock):
        """ Tab directive with a codeblock as its content"""
    
        def run(self):
            self.assert_has_content()
            
            code_block = super().run()[0]
    
            # Set anything required by OtherDirective
    
            node = OtherDirective.run(self)[0]  # Generates container
            node.append(code_block)  # Put code block inside container
    
            return [node]
    

    OtherDirective 是另一个现有指令。

    我无法继承这两个指令并通过super 使用它们的功能,因为我需要从这两个指令中调用一个名为run 的方法。

    更新

    您可以在sphinx-tabsCodeTabDirective 中看到最终解决方案。

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 2019-07-06
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多