I was trying to implement datatables in my Mkdocs material theme. But adding the custome code for datatables doesnt work

Viewed 451

Trying to get datatable into my mkdocs material theme. I tried different ways but it does not work consistently, sometimes work after page-referesh.

mkdocs.yml

extra_css:
  - extra.css
  - https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css

extra_javascript:
  - https://code.jquery.com/jquery-3.5.1.min.js
  - https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js
  - scripts/site.js

scripts/site.js

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

table

<table id="" class="display" style="width:100%">

</table>
1 Answers

Answer: The problem is with scripts/site.js and with the id used in the table. The value 'table.display' in the JavaScript needs to match the <table id=""> value.

If we set them both to something like myTable, then this should be fixed.


Solution:

Markdown file:

## Do data tables work?

<table id="myTable" class="display" style="width:100%">
  <thead><tr><th>Name</th><th>Offices</th></tr></thead>
  <tbody>
    <tr><td>Tiger Nixon</td><td>Edinburgh</td></tr>
    <tr><td>Garrett Winters</td><td>Tokyo</td></tr>
    <tr><td>Ashton Cox</td><td>San Francisco</td></tr>
    <tr><td>Cedric Kelly</td><td>Edinburgh</td></tr>
    <tr><td>Airi Satou</td><td>Tokyo</td></tr>
  </tbody>
</table>

scripts/site.js changed:

$(document).ready( function () {
    $('#myTable').DataTable();
} );

Basically the same mkdocs.yml from above:

extra_css:
  - https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css

extra_javascript:
  - https://code.jquery.com/jquery-3.6.0.slim.min.js
  - https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js
  - scripts/site.js

Then it should work:

A rendered version of data tables embedded in mkdocs.


Thanks for asking this question: I was trying to do exactly what this question proposed and found both this StackOverflow thread and an issue (#2056) listed in the mkdocs-material GitHub repository.


Caveats

Data tables may not work properly with dark/light themes. Here I used the dark slate theme:

Dark theme version of the site, the data table is completely unreadable.

Related