Matteo Matteo - 6 months ago 648
Javascript Question

Setting up a javascript variable from Spring model by using Thymeleaf

How can I read a model variable from

Spring
model and setting up it into a Javascript?

Note that I'm using
Thymeleaf
as Template Engine.

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>

Answer

From the official documentation:

<script th:inline="javascript">
/*<![CDATA[*/

    var message = [[${message}]];
    console.log(message);

/*]]>*/
</script>