Skip to content Skip to sidebar Skip to footer

Dynamically Insert Data Into Javascript Chart Using Thymeleaf

I'm using Google Charts in my webapp. Inside of my controller I pass a object holding data that later I access using method formatData() which returns data formatted to String. Tha

Solution 1:

In thymeleaf 3:

<scripttype="text/javascript"th:inline="javascript">
      /*<![CDATA[*/
      data.addRows( /*[(@{${reco.formatData()}})]*/ );
      /*]]>*/
</script>

Solution 2:

Question already has an (accepted) answer, but here a different viewpoint:

I think there is a misconception of what th:inline="javascript" does. It takes the result of the expression and formats a JavaScript object of it (JSON to be specific I think). If your method returns a String, it will also be a String in the JavaScript code. This is a feature and not a bug.

Alternative solutions:

  • Return the "correct" type from the Java code, not a String. If you want an array in JavaScript, return an array (or List) from Java code.

  • To insert string as is without interception, replace th:inline="javascript" with th:inline="text".

Post a Comment for "Dynamically Insert Data Into Javascript Chart Using Thymeleaf"