Return a HTML formatted content from a renderer

Return a HTML formatted content from a renderer

fgeorgesfgeorges Posts: 8Questions: 3Answers: 0

Hi,

I try to display something else than a simple string using a renderer. The idea is to show a code element, or an a link.

But it seems the result of the rendered is always casted to a string, resulting to [object Object] in my case.

The working, starting point (I know a renderer function is not necessary here, that data: 'foo' would do, but just for the example):

const data = [
    { foo: 'Stuff', bar: 'Things' },
    { foo: 'Stuff', bar: 'Things' },
    { foo: 'Stuff', bar: 'Things' }
];
table.DataTable({
    data: data,
    columns: [
        { title: "Uno", render: function(datum, type, row) {
            return row.foo;
        }},
        { title: "Dos", render: function(datum, type, row) {
            return row.bar;
        }}
    ]
});

If I try to return say, a code element instead of a simple string, in the first rendered above:

return $('<code>' + row.foo + '</code>');

then it is casted to a string (showing [object Object]).

Any idea how I can achieve that?

PS: If I serve the table directly formatted in HTML, with class="datatable", then it just works (but I have to retrieve the source data dynamically from the browser).

Thank you!

--Florent

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,401Questions: 26Answers: 4,787
    Answer ✓

    You should use columns.data to define the data for each column. The use columns.render to build the HTML for display. Also you don't need the $() around the HTMl you want to display.

    Here is an example based on your code:
    http://live.datatables.net/zitubira/1/edit

    Kevin

  • fgeorgesfgeorges Posts: 8Questions: 3Answers: 0
    edited February 2019

    That is what I was missing: we can return HTML but it then must be returned as a plain string.

    So if we have jQuery nodes, we need to serialize them using .html().

    Thank you!

This discussion has been closed.