Karim Belkhiria Karim Belkhiria - 6 months ago 20
HTML Question

rendering DataTable from Json, and modifying one of the columns

I am rendering the rows of a DataTable from a Json-File which get loaded from the server.

One of the columns, contains a link of logos (images), but that link, should not be rendered as plain text, instead of that, as the logo directely.

How could I do that?

Here is my code to render the DataTable:

$(document).ready(function() {
$('#osPartner').DataTable( {
"ajax": "test2.json",
"columns": [
{ "data": "pId" },
{ "data": "sName" },
{ "data": "lgName" },
{ "data": "logo" },
{ "data": "inc" },
{ "data": "feat" }
]
} );
} );


All the data is loaded but the the "logo" column are links. How could I display the images, that are on that link, instead of the link (as text)? Is there a possibility to modify that column, and surround the link with html code, like:

<img src="logo_url_here_that_i_become_from_jsom" alt="Mountain View" style="width:304px">


or

logo = "<img src='"+ logo + "' alt='Mountain View' style='width:304px'>"


Here is how my json-file looks like:

{
"data": [
{
"sName": "hjp",
"lgName": "Hi Ju Pi",
"pId": "lap34208",
"feat": false,
"logo": "https://www.link-here.de/images/image1.png",
"inc": "1°P pro 2€"
},
{
"sName": "hjp2",
"lgName": "Hi Ju Pi22",
"pId": "ldfsdf38",
"feat": false,
"logo": "https://www.link2-here.de/images/image2.png",
"inc": "1°P pro 2€"
}]
}

Answer

You could use a render method :

"columns": [
   { "data": "pId" },
   { "data": "sName" },
   { "data": "lgName" },
   { "data": "logo",
     render : function( data, type, full, meta ) {
       return type == 'display' ? '<img src="'+ data + '"/>' : data
     }
   },
   { "data": "inc" },
   { "data": "feat" }
]

You can get all items for the row through the full variable (if you want to set a certain title or similar for the <img>).