Thymeleaf - Iterating over a model attribute inside Javascript code
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