首页 > 解决方案 > Nested custom directives in sphinx

问题描述

I have a setup where I want to use two custom directives in a nested manner in my rst document:

.. custom_directive_1::

    .. custom_directive_2::
       :argument1: argumenta
       :argument1: argumentb

The contents look as following:

custom directive 1:

class CD1(Directive):
    option_spec = Directive.option_spec
    has_content = True

    def run(self):
        self.assert_has_content()

        #add custom classes to nodes
        node = nodes.container()
        node['classes'].extend(["class1","class2"])
        self.add_name(node)
        self.state.nested_parse(self.content, 2, node)

        for i in node.children:
            i['classes'].extend(["class3","class4"])
    
def setup(app):
    app.add_directive("custom_directive_1", CD1)

    return {
        'version': '0.1',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }

custom directive 2:

def parse_arguments(content):
    arguments = {}
    for item in content:
        item = item.split(":")
        arguments[item[1]] = ":".join(item[2:]).strip()
    return arguments

class CD2(Directive):
    option_spec = Directive.option_spec
    has_content = True

    def run(self):
        self.assert_has_content()
        node = nodes.paragraph()
            arguments = parse_arguments(self.content)
            script_reference = '  <script src="../../_static/path/to/jsfile"></script>'
            new_content = [
                '.. raw:: html', '',script_reference
            ]
            #insert template into other template depending on argument1 input
            with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),"main_template_file.html")) as f:
                main_template_file= f.read()
            with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),"templates","{}.html".format(arguments["argument1"]))) as f:
                figure = main_template_file.format(f.read(),arguments.get("argumentb",""))
            for line in figure.split("\n"):
                new_content.append(line)
            for i,line in enumerate(new_content):
                self.content.data.insert(i, line)
                self.content.items.insert(i, (None, i))
            self.state.nested_parse(self.content, 2, node)
            print(self.content)
            return [node]

def setup(app):
    app.add_directive("custom_directive_2", CD2)

    return {
        'version': '0.1',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }

The problem is that the two arguments passed to directive2 are also being parsed by directive1. When I use .. figure:: inside of directive1 however, the arguments are only interpreted by the figure directive and ignored by directive1. Is there a way to make directive2 behave similarly or to make directive1 only parse the result of directive2?

标签: pythonpython-sphinxrestructuredtextdocutils

解决方案


推荐阅读