Including JavaScript variable inside thymeleaf

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.

Upvotes: 20

Views: 33329

Answers (4)

MrSimple
MrSimple

Reputation: 599

I think I understand your question and I don't think it's possible. Thymeleaf does server side rendering and thus it won't use javascript variables since those won't be created on the server.

What you can try is write an initializer function that will hide/show certain DOM elements. You can approach this multiple ways for instance give ids to them and change their class list to add "display:none" style.

Upvotes: 0

Taugenichts
Taugenichts

Reputation: 1365

With thymeleaf 3, the CDATA block had to be removed to reference my variable inline or the parser ignored it completely. This syntax worked successfully for me post upgrade:

<script th:inline="javascript">
     var myVariable = [[${#vars.myVar}]];
     ...
</script>

Note: if you also referenced your variables as [[${#ctx.variables.myVar}]], it will no longer work in thymeleaf 3 as ctx no longer has a variable named variables.

Upvotes: 1

Saurabh
Saurabh

Reputation: 7833

<script>
   // <![CDATA[
     ...Your script, here
   // ]]>
</script>

Upvotes: -1

geoand
geoand

Reputation: 63991

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.

Upvotes: 35

Related Questions