I want to customize JSON data from back-end before show it with datatables. First I want to replace the spaces ( ) in column artist.name with underscore symbol (_). Then, I want to hyperlink each row in that column with a wiki link like my code.
HTML:
<table id="albums" class="table table-striped table-bordered" style="width:100%" >
<thead>
<tr>
<th>Rank</th>
<th>Artist</th>
<th>Album name</th>
<th>Year</th>
<th>Genres</th>
</tr>
</thead>
</table>
Datatables-JS:
"columns": [
{"data": "rank", "searchable": false},
{
"data": "artist.name".replace(/\s+/g, '_'), // ex: 'The Beatles' => 'The_Beatles'
"name": "artist.name".replace(/\s+/g, '_'),
"render": function (data, name) {
data = '<a href= "https://en.wikipedia.org/wiki/' + name + '">' + name + '</a>'; // render to: https://en.wikipedia.org/wiki/The_Beatles
return data;
}
},
{"data": "name"},
{"data": "year"},
{"data": "genres", "name": "genres.name", "sortable": false},
]
JSON data:
{
"data": [
{
"DT_RowId": "row_1",
"DT_RowAttr": {
"data-pk": 1
},
"rank": 1,
"name": "Sgt. Pepper's Lonely Hearts Club Band",
"year": 1967,
"artist_name": "The Beatles",
"genres": "Psychedelic Rock, Rock & Roll",
"artist": {
"id": 2,
"name": "The Beatles"
}
},
{
"DT_RowId": "row_2",
"DT_RowAttr": {
"data-pk": 2
},
"rank": 2,
"name": "Pet Sounds",
"year": 1966,
"artist_name": "The Beach Boys",
"genres": "Pop Rock, Psychedelic Rock",
"artist": {
"id": 3,
"name": "The Beach Boys"
}
}
...
],
"recordsFiltered": 15,
"recordsTotal": 15,
"draw": 1
}
It does not work. Can anyone help me? Thanks.
dataattribute to a none existing property? There is noThe_Beatlesproperty in the JSON. The result would be an error. And even if there were aThe_Beatlesindex it does not add up, since you would in fact try to change thenameortitleof the column multiple times according to row data. Columns can only have one title and one name.render(hyperlink) incolumn? @davidkonrad