Setting up a JavaScript variable from Spring model by using Thymeleaf

Matteo picture Matteo · Sep 5, 2014 · Viewed 146.3k times · Source

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>

Answer

vdenotaris picture vdenotaris · Sep 5, 2014

According to the official documentation:

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

    var message = /*[[${message}]]*/ 'default';
    console.log(message);

/*]]>*/
</script>