Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a JavaScript variable from Spring model by using Thymeleaf

I am using Thymeleaf as template engine. How I pass a variable from Spring model to JavaScript variable?

Spring-side:

@RequestMapping(value = "message", method = RequestMethod.GET) public String messages(Model model) {     model.addAttribute("message", "hello");     return "index"; } 

Client-side:

<script>     ....     var m = ${message}; // not working     alert(m);     ... </script> 
like image 838
Matteo Avatar asked Sep 05 '14 14:09

Matteo


People also ask

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 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.

How do you set 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.


2 Answers

According to the official documentation:

<script th:inline="javascript"> /*<![CDATA[*/      var message = /*[[${message}]]*/ 'default';     console.log(message);  /*]]>*/ </script> 
like image 126
vdenotaris Avatar answered Sep 23 '22 13:09

vdenotaris


Thymeleaf 3 now:

  • Display a constant:

     <script th:inline="javascript"> var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ ""; </script> 
  • Display a variable:

     var message = [[${message}]]; 
  • Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).

    Thymeleaf calls this: JavaScript natural templates

     var message = /*[[${message}]]*/ ""; 

    Thymeleaf will ignore everything we have written after the comment and before the semicolon.

More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining

like image 24
redochka Avatar answered Sep 23 '22 13:09

redochka