From Thymeleaf 3, it is possible to output a string without escaping in JavaScript (or rather inline processing).
You can use [(...)]
instead of [[...]]
.
HTML
<script th:inline="javascript">/*<![CDATA[*/
var foo = /*[(${foo})]*/ {"bar":"drei","baz":"]]\u003e"\n'<\u002fscript\u003e"};
/*]]>*/</script>
Controller (Spring)
@GetMapping("/")
public Object index(Model model) throws IOException {
final MyForm myForm = new MyForm("", "'\"&</script>]]>", Optional.of(LocalDateTime.now()));
model.addAttribute("foo", this.objectMapper.writeValueAsString(myForm));
return "index";
}
[^ 1]: This example customizes ObjectMapper to escape /
and >
. This is to avoid the </ script>
tag and ]]>
.
<script>/*<![CDATA[*/
var contextPath = "\/";
var foo = {"baz":"","cux":"'\"&<\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.
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