Search code examples
python-sphinxrestructuredtext

restructuredtext include partial rst directives from other files (i.e. templates)


I'm looking for a way to include partial rst directives from another file.

I have some restructured text files that have repeating table definitions, and I would like to make this a reusable template to avoid redefining the same table again and again.

multiple files list tables that all start like to following (i.e. common settings and header) but the actual data rows afterwards differ.

.. list-table::
    :align: left
    :header-rows: 1
    :width: 100%
    :widths: 25 25 25 25

    * - ColumnHeader1
      - ColumnHeader2
      - ColumnHeader3
      - ColumnHeader4

The include directive does not seem to work for this, as it will parse the line-table and then include the result, I cannot add additional rows to that line-table afterwards.

Is there any way that I could achieve this?

EDIT: Forgot to mention that I use restructuredtext as part of sphinx. It seems it is quite easy to extend sphinx: https://www.sphinx-doc.org/en/master/development/tutorials/helloworld.html

EDIT2: Moved my solution to an answer to this question


Solution

  • I found a way to implement this as a sphinx extension (following this tutorial https://www.sphinx-doc.org/en/master/development/tutorials/helloworld.html)

    from docutils.parsers.rst.directives.tables import ListTable
    from docutils.statemachine import ViewList
    
    
    class MyTable(ListTable):
        def run(self):
            header_rows = ViewList([
              '* - ColumnHeader1',
              '  - ColumnHeader2',
              '  - ColumnHeader3',
              '  - ColumnHeader4',
            ])
            self.content = header_rows + self.content
    
    
            self.options['header-rows'] = 1
            self.options['width'] = '100%'
            self.options['widths'] = '25 25 25 25'
            self.options['align'] = 'left'
            return super().run()
    
    
    def setup(app):
        app.add_directive('my-table', MyTable)
    
        return {
            'version': '0.1',
            'parallel_read_safe': True,
            'parallel_write_safe': True,
        }
    

    This let's me define tables like this now:

    .. my-table::
    
        * - Column 1
          - Column 2
          - Column 3
          - Column 4