Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 473
Deepak Ramakrishnan Kalidass Avatar asked Mar 22 '14 08:03

Deepak Ramakrishnan Kalidass


People also ask

How do you add JavaScript to Thymeleaf?

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.

Can we use JavaScript with Thymeleaf?

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.

How do I declare a variable in Thymeleaf?

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.

How do you write a script for Thymeleaf?

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.


1 Answers

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.

like image 144
geoand Avatar answered Oct 19 '22 04:10

geoand