Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function call with Thymeleaf

Tags:

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

like image 779
f4root Avatar asked Oct 23 '14 10:10

f4root


People also ask

How do you call a function in Thymeleaf?

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.

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. The main goal of Thymeleaf is to provide an elegant and highly-maintainable way of creating templates.

How do I use onclick in Thymeleaf?

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.

How do you use Thymeleaf?

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.


2 Answers

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.

like image 170
Tom Bunting Avatar answered Sep 21 '22 13:09

Tom Bunting


You need to call the javascript function as mentioned below.

th:onclick="'javascript:function1(\''+ ${a} +'\');'" 

I think this could help you.

like image 21
Newbie Avatar answered Sep 18 '22 13:09

Newbie