Search code examples
javatemplatesencodingthymeleaf

Avoid special character escaping in Thymeleaf with Java


I am trying to use Thymelead as a template engine for some text templates that I have.

My template looks like this

free text 
[[${myVar}]]
more text

My Java code is

ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TEXT);

TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context(ENGLISH, null);
context.setVariable("myVar", "My text with special characters such as ' < > &");
System.out.println(templateEngine.process("templateFileName", ctx));

I am expecting the above to print

free text 
My text with special characters such as ' < > &
more text

but instead it prints

free text 
My text with special characters such as &#39; &lt; &gt; &amp;
more text

Since I am working on plain text and not HTML or XML shouldn't it print the special characters unescaped ?

I have set mode to TEXT and encoding to UTF-8.

Please enlighten me.

Thanks

Nick


Solution

  • You should use [(${myVar})] to print the text unescaped.

    (I do agree that it's weird that [[${...}]] expressions escape HTML special characters in TEXT template mode.)