Including JavaScript variable inside thymeleaf

Deepak Ramakrishnan Kalidass picture Deepak Ramakrishnan Kalidass · Mar 22, 2014 · Viewed 26.4k times · Source

How do I include a JavaScript variable inside thymeleaf for checking a condition?

Tried:

<div th:if="${myVariable == 5}">
 //some code
</div>

but it's not working.

Answer

geoand picture geoand · Mar 22, 2014

What you are trying to do won't work, since Thymeleaf processes the template on the server side and therefore the variables it has access to are the ones defined in it's model.

If you had myVariable in the model on which Thymeleaf is operating, it would work. If what you want is to set the value of a Javascript variable in a Thymeleaf template, you can do the following:

<script th:inline="javascript">
/*<![CDATA[*/
    ...

    var myVariable= /*[[${myVariable}]]*/ 'value';

    ...
/*]]>*/
</script>

Inside the script you could have any logic you want including hide/show etc.

Check out this part of the documentation for mode details.