yglodt
yglodt

Reputation: 14551

Thymeleaf forEach loop in JavaScript

I am migrating a project from JSP to Thymeleaf.

In some JSPs I did fancy stuff like this:

<script type="text/javascript">
    //<c:forEach items="${pages}" var="page">

    ...
    var l = new google.maps.LatLng("${page.lat}", "${page.long}");
    ...

    //</c:forEach>
</script>

How could I do the same with Thymeleaf?

Upvotes: 7

Views: 13575

Answers (2)

yglodt
yglodt

Reputation: 14551

This is the working solution with Thymeleaf 3.0.2:

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

    /*[# th:each="page : ${pages}"]*/
        ...
        var l = new google.maps.LatLng(/*[[${page.lat}]]*/, /*[[${page.long}]]*/);
        ...
    /*[/]*/

/*]]>*/
</script>

Why and how it works is explained here: [MAJOR FEAT] New syntax for textual template modes #395

Upvotes: 13

Aliaksei Stadnik
Aliaksei Stadnik

Reputation: 1968

You can write out the attribute to

<span id="myvar" th:text="${attributeName}"></span>

Then you can access it with JS as :

document.getElementById("myvar") or jquery $('#myvar').text()

Thymeleaf code is running on server side and JS code on client side. I am wondering how does jsp hadle this staff without any tricks.

Upvotes: 0

Related Questions