Output JavaScript in Thymeleaf 3 without escaping

From Thymeleaf 3, it is possible to output a string without escaping in JavaScript (or rather inline processing). You can use [(...)] instead of [[...]].

Example

HTML

<script th:inline="javascript">/*<![CDATA[*/
  var foo = /*[(${foo})]*/ {"bar":"drei","baz":"]]\u003e&quot;\n'<\u002fscript\u003e"};
/*]]>*/</script>

Controller (Spring)

@GetMapping("/")
public Object index(Model model) throws IOException {
  final MyForm myForm = new MyForm("", "'\"&amp;</script>]]>", Optional.of(LocalDateTime.now()));
  model.addAttribute("foo", this.objectMapper.writeValueAsString(myForm));
  return "index";
}

=> Output [^ 1]

[^ 1]: This example customizes ObjectMapper to escape / and >. This is to avoid the </ script> tag and ]]>.

<script>/*<![CDATA[*/
  var contextPath = "\/";
  var foo = {"baz":"","cux":"'\"&amp;<\u002Fscript\u003E]]\u003E","datetime":"2017-10-16T23:26"};
/*]]>*/</script>

If you pass the object to Thymeleaf as it is and serialize it, LocalDate etc. (JSR-310 related) will be converted, but Optional seems to be unsupported.

Bonus: Dependency settings in build.gradle

In case of Spring Boot 1.5 series, the reference destination of spring-boot-starter-thymeleaf is Thymeleaf 2, so it is necessary to specify the dependency separately.

def thymeleafVersion = '3.0.7.RELEASE'
// https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4
compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: thymeleafVersion
// https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
compile group: 'org.thymeleaf', name: 'thymeleaf', version: thymeleafVersion

After that, AutoConfiguration works and it will do it for you.

Recommended Posts

Output JavaScript in Thymeleaf 3 without escaping
How to embed JavaScript variables in HTML with Thymeleaf
Output triangle in Ruby
Generate JavaScript with Thymeleaf
Output in multiples of 3
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
Try calling JavaScript in Java
Refer to enum in Thymeleaf
Use ruby variables in javascript.
Supports 0 drop in CSV output
Format Timestamp type in Thymeleaf