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>
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 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.
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.
According to the official documentation:
<script th:inline="javascript"> /*<![CDATA[*/ var message = /*[[${message}]]*/ 'default'; console.log(message); /*]]>*/ </script>
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
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