I need to call a javascript function on thymeleaf template, something like this:
Case 1:
<select th:onclick="${'function1('a')'}">
But in this case the thymeleaf not work.. some researchs ago (including stackoverflow) I get the followings "solutions":
Case 2:
<select th:onclick="${'function1(''a'')'}">
Case 3:
<select th:onclick="${'function1(\'a\')'}">
Case 4:
<select th:onclick="${'function1(\''+'a'+'\')'}">
But in all cases I get the same error: "...Exception evaluating SpringEL expression..."
My problem is about javascript callings, I need put some parameters ${var} for call in js function. How I can fix that ?
Thanks
Thymeleaf does not work like JSP. It works by extending existing HTML elements with new attributes prefixed by "th:". And you can reference variables (and therefore call method on them) only in theses extra-attributes. But <p>${contentOfTheParagraph}"</p> will not.
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. The main goal of Thymeleaf is to provide an elegant and highly-maintainable way of creating templates.
10, thymeleaf doesn't support variables of type other than Boolean and Integer inside th:onclick="..." . So if you want to pass a non-boolean and non-integer argument to the onclick() method, th:onclick="..." won't work. You have to use th:attr="onclick=..." as shown in this answer.
You can use Thymeleaf templates to create a web application in Spring Boot. You will have to follow the below steps to create a web application in Spring Boot by using Thymeleaf. In the above example, the request URI is /index, and the control is redirected into the index. html file.
If you don't need any dynamic vars in the JS function call, this is how to do it:
th:onclick="'alert(\'a\');'"
This simply escapes the single quotes and requires no SpringEL (of course you could dispense with the thymeleaf attribute in this case and just use plain onclick).
To insert vars into it:
th:onclick="'alert(\'' + ${myVar} + '\');'"
Used the alert function to allow me to try it out and prove it works. Hope that helps.
You need to call the javascript function as mentioned below.
th:onclick="'javascript:function1(\''+ ${a} +'\');'"
I think this could help you.
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