Setting up a JavaScript variable from Spring model by using Thymeleaf

190,396

Solution 1

According to the official documentation:

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

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

/*]]>*/
</script>

Solution 2

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

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

Solution 4

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 5

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

Share:
190,396
Matteo
Author by

Matteo

Updated on July 08, 2022

Comments

  • Matteo
    Matteo almost 2 years

    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>
    
  • szxnyc
    szxnyc over 9 years
    Doesn't work... javascript error uncaught syntax error
  • Andrew
    Andrew over 9 years
    Works fine, also possible to read from messages.properties: var msg = [[#{msg}]];
  • jyu
    jyu over 8 years
    Notice it should be NO space between /* */ and the contained [[ ]].
  • CodeMonkey
    CodeMonkey over 7 years
    @szxnyc if you forget the /*<![CDATA[*/ macro you will get that.
  • Felipe Leão
    Felipe Leão about 7 years
    It's worth noting that the defaultanyvalue will only be used when running the page statically, i.e. outside a web container. If ran inside a container and the variable message hasn't been declared the resulting source code will be var message = null;
  • Grigory Kislin
    Grigory Kislin almost 7 years
    Also take attention to <script th:inline="javascript">
  • redent84
    redent84 almost 6 years
    Also important to add th:inline="javascript" to the script tag.
  • Michał Stochmal
    Michał Stochmal over 5 years
    How to make it work when using external script viath:src="@{/js/script.js}" ?
  • Aung Aung
    Aung Aung over 5 years
    thanks you! wanna gave you a beer i was looking for this syntax var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
  • Alfaz Jikani
    Alfaz Jikani over 4 years
    @MichałStochmal you can load inline javascript on top of external javascript and use same variables(defined in inline javascript) in external javascript.
  • JustTry
    JustTry over 4 years
    this works for me // <![CDATA[ var abc = 'somepath?someParam=[[${fromController}]]' ; // ]]>
  • Phil Freihofner
    Phil Freihofner about 3 years
    This should get more votes, now that Thymeleaf 3 is pretty much the norm, yes? The manual link should also be updated. thymeleaf.org/doc/tutorials/3.0/… ...I just shipped a float[] with audio data to a web page for the first time. Can play it with Web Audio API! This question and these answer were a big help in locating the Javascript inlining used.