Setting up a JavaScript variable from Spring model by using Thymeleaf

JavascriptSpringThymeleaf

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

According to the official documentation:

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

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

/*]]>*/
</script>

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.

  1. Simply put the variable from server to javascript :

  2. Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:

The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).

Solution 5 - Javascript

MAKE sure you have thymleaf on page already

//Use this in java
@Controller
@RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
 model.addAttribute("showTextFromJavaController","dummy text");
 return "showingTymleafTextInJavaScript";
}


//thymleaf page  javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>

Solution 6 - Javascript

I've seen this kind of thing work in the wild:

<input type="button"  th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />

Solution 7 - Javascript

If you use Thymeleaf 3:

<script th:inline="javascript">
    var username = [[${session.user.name}]];
</script>

Solution 8 - Javascript

Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html

> One way to handle this is to create a dynamic javascript file with the > URLs embedded in it. Here are the steps (if you are using Spring MVC)

@RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public String dynamicJS(HttpServletRequest request) {

		return "Your javascript code....";

}


  

Solution 9 - Javascript

If you need to display your variable unescaped, use this format:

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

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

/*]]>*/
</script>

Note the [( brackets which wrap the variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatteoView Question on Stackoverflow
Solution 1 - JavascriptvdenotarisView Answer on Stackoverflow
Solution 2 - JavascriptredochkaView Answer on Stackoverflow
Solution 3 - Javascriptuser5518390View Answer on Stackoverflow
Solution 4 - JavascriptsanluckView Answer on Stackoverflow
Solution 5 - JavascriptNitish KanadeView Answer on Stackoverflow
Solution 6 - JavascriptNoumenonView Answer on Stackoverflow
Solution 7 - JavascriptTogrul SadigovView Answer on Stackoverflow
Solution 8 - JavascriptPaolo BiavatiView Answer on Stackoverflow
Solution 9 - Javascriptmichal.jakubeczyView Answer on Stackoverflow