Search code examples
htmlsortingpython-sphinxrestructuredtext

Sorting table with rst and python-sphinx in html output


I'd like to offer my visitors the possibility to sort the cells in the tables in an HTML page generated from RST with python-sphinx. Let's suppose I have a table like this:

.. list-table:: A fancy name table
   :header-rows: 1
   
   * - Family name
     - Given name
   * - Smith
     - Samuel
   * - Johnson
     - John

This renders well and shows the name in the order of the input. Now I'd like to generate an HTML output and offer the user the possibility to reorder the names into alphabetical order. There are standalone examples and libraries to implement this, and I'd like to know which solution has already implemented into Sphinx if any. The best would be to include a minimal extension and modify a property of all the tables (or just the one I'd like to be able to sort) to include this feature.

Could you please advise an extension and best practice how to do it? I'd prefer to make the least possible CSS and JS code/file manipulation myself.


Solution

  • Inspired by some answers already provided I created the following solution which uses dataTables. I am using the html theme 'classic' which already includes jquery (I'm not sure about the other templates).

    In conf.py add additional css and js files:

    html_static_path = ['_static']
    
    html_css_files = [
        'https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css',
    ]
    
    html_js_files = [
        'https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js',
        'main.js',
    ]
    

    Create the file _static/main.js and add the following lines (I've chosen to use a class "datatable" to explicitly enable this feature on a table):

    $(document).ready( function () {
        $('table.datatable').DataTable();
    } );
    

    In your rst document you can now create a fancy table:

    .. table::
       :class: datatable
    
       =====  =====  =======
       A      B      A and B
       =====  =====  =======
       False  False  False
       True   False  False
       False  True   False
       True   True   True
       =====  =====  =======
    

    The :class: datatable adds a class to the table element, consequently the DataTable javascript is applied on this table.