Deokkee Min
Deokkee Min

Reputation: 25

Thymeleaf - Unquoting a part of inline JavaScript expression

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.

Upvotes: 1

Views: 1159

Answers (2)

Deokkee Min
Deokkee Min

Reputation: 25

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.

Upvotes: 1

M. Prokhorov
M. Prokhorov

Reputation: 3993

[[...]] 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

Upvotes: 1

Related Questions