0

In controller I put simple java object, mapped to JSON using jackson.

    Station station = stationRepo.findFirstByCodeEquals(320007);

    ObjectMapper objectMapper = new ObjectMapper();
    String JSONstation = objectMapper.writeValueAsString(station);
    model.addAttribute("station",JSONstation);

In front end I use Thymeleaf to get this object in tag:

<p id="test" th:text="${station}">Test 1</p>
<p id="test2">Test 2</p>
<p id="test3">Test 3</p>

And I simply get this JSON object in javascript using document.getElementById("test").innerText, and parse it into js object.

    var JSONtest = "[[${station}]]";
    var JSONstation = document.getElementById("test").innerText;

    document.getElementById("test2").innerHTML = typeof JSONtest;

    var jsStation = JSON.parse(JSONstation);


    document.getElementById("test3").innerHTML = JSONtest.rusName;

But when I thy to get JSON object from thymeleaf using var JSONtest = "[[${station}]]" I can`t parse it into js object, but they are the same. What am I do wrong in this code?

1
  • 1
    I think you meant var JSONtest = `[[${station}]]`; - you need to enclose the string in backticks to use the ${..} interpolation syntax Commented Mar 27, 2019 at 14:30

1 Answer 1

3

When you are using Thymeleaf variables in JavaScript, you shouldn't pass them as a String. Instead you should add the variable to the model as you normally would:

model.addAttribute("station", station);

and let Thymeleaf automatically translate it to JavaScript (it will handle the translation of your object to JSON, no need for you to use Jackson):

<script th:inline="javascript">
    var JSONtest = /*[[${station}]]*/ {};
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Great, it's simpler than i thought. I just walk thru such construction because I thought that it is commented block of code.

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.