How do I include a JavaScript variable inside thymeleaf for checking a condition?
<div th:if="${myVariable == 5}">
//some code
</div>
but it's not working.
We load the stylesheet using the link tag with Thymeleaf's special th:href attribute. If we've used the expected directory structure, we only need to specify the path below src/main/resources/static. In this case, that's /styles/cssandjs/main. css.
Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
We can use the th:with attribute to declare local variables in Thymeleaf templates. A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it.
Thymeleaf evaluates the expression and assigns the value to a variable. To facilitate it, we need to use th:inline="javascript" as an attribute in <script> tag. Thymeleaf syntax to evaluate expression is written using javascript comment, so that while running offline, Thymeleaf expression will not be displayed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With