In the columnDefs
option of datatable I want to render a link with thymeleaf
:
datatable = table.DataTable({
...,
columnDefs: [
{
targets: [4],
orderable: false,
searchable: false,
render: function(data, type, row, meta) {
const id = row[0];
return '<div style="display: flex; align-items: center;">'+
'<div class="col-sm-3"></div>'+
'<a th:href="@{/grilletarif/view/{id} (id='+id+')}">voir</a>'+
'<div class="col-sm-3"></div>'+
'<img class="icone_row_action" src="icones/delete.png" onclick="javascript:delete('+id+');" />'+
'<div class="col-sm-3"></div>'+
'</div>';
}
}
],
...
});
But at runtime the link is not rendered, and when I inspect the element then I get : <a th:href="@{/grilletarif/view/{id} (id=01)}">voir</a>
So what is wrong ?
Thymeleaf doesn't normally parse attributes inside tags. And it definitely doesn't let you use JavaScript variables (like const id = row[0];
) in Thymeleaf expressions like you are doing here: th:href="@{/grilletarif/view/{id} (id='+id+')}"
(Thymeleaf doesn't know anything about JavaScript, and has already run by the time this code executes).
If you want to create this link, you'll need to use JavaScript inlining. Something like this for example:
<script th:inline="javascript">
const url = /*[[@{/grilletarif/view/}]]*/ "";
datatable = table.DataTable({
...,
columnDefs: [{
targets: [4],
orderable: false,
searchable: false,
render: function(data, type, row, meta) {
const id = row[0];
return '<div style="display: flex; align-items: center;">'+
'<div class="col-sm-3"></div>'+
'<a href="' + url + id '">voir</a>'+
'<div class="col-sm-3"></div>'+
'<img class="icone_row_action" src="icones/delete.png" onclick="javascript:delete('+id+');" />'+
'<div class="col-sm-3"></div>'+
'</div>';
}
}],
...
});
</script>