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.
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
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>
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With