3

I'm trying to write a basic extension to create a new directive (output) based on the only directive provided by Sphinx. This new directive simply needs to add an HTML class to the standard result of the Only directive.

So for this I have tried the following code based on this collapse-code-block extension.

Since docutils has virtually no documentation and that I'm not a very experienced python developer, I'm struggling to make this work.

Here is what I have tried, amongst other variations that all led to no real indication on the issue:

from docutils import nodes

from sphinx.directives.other import Only


class output_node(nodes.General, nodes.Element):
    pass


class output_directive(Only):

    option_spec = Only.option_spec

    def run(self):
        env = self.state.document.settings.env

        node = output_node()
        output = Only.run(self)
        node.setup_child(output)
        node.append(output)

        return [node]


def html_visit_output_node(self, node):
    self.body.append(self.starttag(node, 'div', '', CLASS='internalonly'))


def html_depart_output_node(self, node):
    self.body.append('</div>')


def setup(app):
    app.add_node(
        output_node,
        html=(
            html_visit_output_node,
            html_depart_output_node
        )
    )
    app.add_directive('output', output_directive)

I don't think it should be more complicated than that but this just doesn't cut it.

Any idea?

mzjn
  • 48,958
  • 13
  • 128
  • 248
Flag
  • 497
  • 1
  • 3
  • 17
  • Why not use the [`:class:` attribute](http://docutils.sourceforge.net/docs/ref/rst/directives.html#class)? In Sphinx it is called [`rst-class`](http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#id1). – Steve Piercy Jul 12 '18 at 20:48
  • That would mean more chances of errors. With an extension, I control the output class name, not the user. – Flag Jul 16 '18 at 13:26
  • Hey Flag, the code from your question has helped me a lot to generate custom container (div with custom tags) that I needed for my custom directive. Thanks a lot! – Stanislav Pankevich May 01 '20 at 18:06
  • What do you mean by "this just doesn't cut it"? – Amos Egel May 25 '20 at 08:35

0 Answers0