[javascript] Setting up a JavaScript variable from Spring model by using Thymeleaf

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 related to javascript spring thymeleaf

The answer is


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 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.


If you use Thymeleaf 3:

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

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>

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

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

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

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....";

}


  

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 :

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

var message = [[${message}]];
alert(message);

/*]]>*/
</script>

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

<script th:inline="javascript">
        /*<![CDATA[*/
        function sampleGetByJquery(v) {
            /*[+
            var url = [[@{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]] 
                      + "&var2="+v;
             +]*/
            $("#myPanel").load(url, function() {});
        }
        /*]]>*/
        </script>

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).


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to thymeleaf

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers Setting up a JavaScript variable from Spring model by using Thymeleaf Thymeleaf: how to use conditionals to dynamically add/remove a CSS class How to set thymeleaf th:field value from other variable Using Thymeleaf when the value is null How to avoid the "Circular view path" exception with Spring MVC test Thymeleaf: Concatenation - Could not parse as expression How to do if-else in Thymeleaf?