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

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.