Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Escape double square brackets for Thymeleaf

I am using Thymeleaf + Datatables.js.

I want to apply the default ordering on my datatable in javascript, like so:

<script type="text/javascript" th:inline="javascript" class="init">

/*<![CDATA[*/

$(document).ready(function() {
    $('#myTable').DataTable({
        "order" : [[ 0, 'asc' ]]
    });
});

/*]]>*/

</script>

However, I get the following exception caused by Thymeleaf:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: " 0, 'asc' "

So even though I placed my js code into

/*<![CDATA[*/ ... /*]]>*/

Thymeleaf still wants to parse it as an expression. How do I escape the double square brackets?

like image 943
hooch Avatar asked May 15 '18 16:05

hooch


2 Answers

You could move it into it's own block:

<script type="text/javascript" th:inline="none" class="init">
/*<![CDATA[*/
$(document).ready(function() {
    $('#myTable').DataTable({
        "order" : [[ 0, 'asc' ]]
    });
});
/*]]>*/
</script>

<script type="text/javascript" th:inline="javascript" class="init">
/*<![CDATA[*/
// other javascript with thymeleaf variables in it goes here
/*]]>*/
</script>

You can format the order differently:

$('#myTable').DataTable({
    "order" : [
      [ 0, 'asc' ]
    ]
});

or

$('#myTable').DataTable({
    "order" : [ [ 0, 'asc' ] ]
});
like image 62
Metroids Avatar answered Oct 21 '22 12:10

Metroids


As of Thymeleaf 3 you may also add the attribute th:inline="none" to your script-tag (or any other tag in the DOM-tree if you want to apply it to all its children).

See: Disabling inlining in the Thymeleaf 3 Doc

like image 25
TyPh00n Avatar answered Oct 21 '22 12:10

TyPh00n