I have several tables that I’d like to include in my forum and your approach works perfectly. I’ve created this theme component initializer file:
import { apiInitializer } from 'discourse/lib/api';
import loadScript from 'discourse/lib/load-script';
export default apiInitializer('0.11.1', (api) => {
api.decorateCookedElement(
(elem, helper) => {
const dataTables = $('[data-wrap="dataTables"] table', elem);
if (!dataTables.length) return;
loadScript('https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js').then(
() => {
$.fn.dataTable.ext.errMode = 'throw';
dataTables.dataTable({
ajax: {
url:
'https://gist.githubusercontent.com/USERNAME/MY_GIST_ID/raw/data.json',
dataSrc(data) {
return data.map((x) => {
return {
id: x.my_id,
title: `${x.number} - ${x.title}`,
};
});
},
},
columns: [
{ data: 'id', title: 'My ID' },
{ data: 'title', title: 'My Title' }
],
dom: 'Bfrt',
});
}
);
},
{ id: 'discourse-my-custom-data-tables', onlyStream: true }
);
});
And I load the table in the post using this:
[wrap=dataTables]
<table></table>
[/wrap]
However, there are multiple things I’d like to customize for each table and I’m not sure how to go about it.
For example:
-
I’d like to use a different Gist Id for each table. That should be easy enough by passing an attribute to the wrap and then accessing it with
elem.children[0].dataset.gist:[wrap=dataTables gist="some_gist_id"] <table></table> [/wrap] -
But what if I want multiple tables, each with different processing code in the
dataSrcfunction or differentcolumnordomparameters?Is there a way to pass a JS config file to
dataTables.dataTable()?