Setting up a JavaScript variable from Spring model by using Thymeleaf

121

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>

This question is tagged with javascript spring thymeleaf

~ Asked on 2014-09-05 14:08:15

The Best Answer is


214

According to the official documentation:

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

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

/*]]>*/
</script>

~ Answered on 2014-09-05 14:33:23


20

var message =/*[[${message}]]*/ 'defaultanyvalue';

~ Answered on 2015-11-03 03:55:33


Most Viewed Questions: