7

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?

2 Answers 2

13

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

0

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.

1
  • Thanks for your hint, though I am not sure that it will work, since I want to generate JavaScript and not html. I'll try this evening. About your remark concerning JSPs: You gave the explanation yourself. It works because the JSP engine processes the page on the server, and generates the JavaScript inside the page, which the browser gets sent. The page in action is here tessyglodt.lu/kaart and the sourcecode is here github.com/yglodt/tessyglodt.lu/blob/master/src/main/webapp/…
    – yglodt
    Commented Dec 28, 2016 at 13:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.