简体   繁体   中英

Thymeleaf - Iterating over a model attribute inside Javascript code

I'm trying to write some Javascript code where I need to use a model attribute. Here is how I define the script tag:

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

    //need some loops

    /*]]>*/
</script>

What I need to do is, using each iterations over model attributes inside the script. So far I couldn't manage to do this with th:each . Any help is appreciated.

I guess you need to wrap your model attrubite in double brackets, like this: [[${modelAttribute}]] . The script inlining section of the Thymeleaf docs can help a bit: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart

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

    var theList = [[${modelAttribute}]]
    for (i = 0; i < theList.length; i++) {
        doSomething(theList[i]);
    }

    /*]]>*/
</script>

You can also do like this, which is the most compact I guess:

In your @Controller :

model.addAttribute("items", new String[] { "item1", "item2", "item3" });

In your template:

<script type="text/javascript" th:inline="javascript">

var items = [];

/*[# th:each="n : ${items}"]*/

items.push("[(${n})]");

/*[/]*/

</script>

Other useful stuff is explained here: [MAJOR FEAT] New syntax for textual template modes #395

Thymeleaf 3 -> see yglodt answer

if you're stuck with Thymeleaf 2 and your model attribute is complex (like the case of Maxime Laval), I ended up looping over a script :

<script th:inline="javascript">
  var dataLayer = [];
</script>
<script th:each="item:${items}" th:inline="javascript">
  dataLayer.push({'attr1':item.attr1, 'attr2':item.attr2, 'attr3':item.attr3});
</script>
<script th:inline="javascript">
  console.log(dataLayer); // do whatever you want with dataLayer...
</script>

Not very nice but I couldn't find better for my Google analytics.

This works with me in latest version of thymeleaf by adding /*[[${name}]]*/

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

    var theList = /*[[${modelAttribute}]]*/
    for (i = 0; i < theList.length; i++) {
        doSomething(theList[i]);
    }

    /*]]>*/
</script>

thymeleaf converts object into javascript variable within the script tag, so can access properties using javascript codes. no need to worry about th:

     <script type="text/javascript" th:inline="javascript">
                            /*<![CDATA[*/
                            //the list converts as a javascript object
                            var availableTypes = /*[[${dataList}]]*/;
                            console.log(availableTypes);
                            /*]]>*/
     </script>

在此处输入图片说明

Another approach if you are stuck with Thymeleaf 2 is absusing the "th:block"-Element within your Script-Tag

<script type="text/javascript">
        var arrayOfIds= [
        <th:block th:each="element: ${list}" th:inline="text">[[${element.Id}]],</th:block>
            -1 
        ];
        arrayOfIds.pop(); // Remove the superflous last Element
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM