5

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 2

8

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

So

<script th:inline="javascript">
/*<![CDATA[*/
[(${myCode})]
/*]]>*/
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Finally I got it.

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

1 Comment

I know this is a totally old post, however right now I'm trying to figure out what's going on here. So how did you manage to make this snippet workable? At the time of development I'm getting tons of errors when I try to write such code. At the runtime I'm getting empty (not even null) value there.

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.