[英]How can I use an existing Directive within a custom python-sphinx Directive/extension?
我想創建一個自定義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
我如何以獨立於解析器的方式實現它?
最后,我的解決方案是:
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-tabs
的CodeTabDirective中看到最終解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.