1

I have a Spring Boot project, and I need to render a part of a script element like the following. (Assume that getMessage function is defined somewhere else.)

Expected output:

<script type="text/javascript">
    /*<![CDATA[*/
    var message = 'Hello, John' + getMessage();
    alert(message);
    /*]]>*/
</script>

where John is a Spring model attribute.

Is it possible to make the whole 'Hello, John' + getMessage() in a single Thymeleaf expression? Or, is assigning Hello, John and getMessage() to separate JavaScript variables then concatenating them the only way? I tried something like the following but it seems inlined JavaScript expression always gets quoted.

<script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/
    var message = /*[[|'Hello, ${name}' + getMessage()|]]*/ 'Hello, John';
    alert(message);
    /*]]>*/
</script>

Actual output:

<script type="text/javascript">
    /*<![CDATA[*/
    var message = "'Hello, John' + getMessage()";
    alert(message);
    /*]]>*/
</script>

By the way, I'm using Thymeleaf 2.1.

2 Answers 2

1

[[...]] notation is used for escaped inlining: it converts everything inside into a well-formed Javascript string.

Since you also want to call something, you need un-inlined version, using [(...)] notation:

var message = /*[('Hello, ${name}' + getMessage())]*/ 'Hello, John';

Do note, however, that this way you won't get automatically escaped string, so if ${name} contains single quote char ('), you will get malformed javascript expression. You will need to deal with this somehow.

More info: Thymeleaf: Javascript Inlining

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

4 Comments

Thanks. /*[(|'Hello, ${name}' + getMessage()|)]*/ (with pipes) seems to be the way to go. Although, I should have clarified I'm using Spring Boot 1.5 which depends on Thymeleaf 2.1, and Thymeleaf 2.1 doesn't seem to understand [(...)] notation.
The [(...)] notation seems to be the new feature of Thmeleaf 3. github.com/thymeleaf/thymeleaf/issues/394
@DeokkeeMin, pipe is the literal substitution, so I think you would replace ' chars with it, not just surround the thing. Come to think of it, try that without [()] notation.
Using pipes without [[...]] or [(...)] (i.e., /*|...|*/) didn't work. Apparently Thymeleaf doesn't pick it up as an expression.
1

Found that by using the special comment syntax /*[+...+]*/ I could unquote the part following the thymeleaf expression.

/*[+
var message = [[|Hello, ${name}|]] + getMessage();
+]*/

Result:


var message = 'Hello, John' + getMessage();

Works on Thymeleaf 2.1.

Comments

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.