How to inline JavaScript with Thymeleaf

Viewed 6536

I would like to use Thymeleaf to do inline Javascript.

For example:

<script th:inline="javascript">
/*<![CDATA[*/
  /*[[${myCode}]]*/;
/*]]>*/
</script>

and in Spring Boot I have this:

model.addAttribute("myCode", "alert("test")");

My output HTML is:

<script th:inline="javascript">
/*<![CDATA[*/
  "alert("test")";
/*]]>*/
</script>

which is a string. What am I doing wrong?

2 Answers

When inlining, [[...]] corresponds to th:text and [(...)] corresponds to th:utext.

So

<script th:inline="javascript">
/*<![CDATA[*/
[(${myCode})]
/*]]>*/
</script>

Finally I got it.

<script th:inline="javascript">
/*<![CDATA[*/
[#th:block th:utext="${myCode}" /]
/*]]>*/
</script>
Related