简体   繁体   中英

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

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.)

Change your template from:

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

...to:

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

As stated in Thymealeaf's documentation :

Expressions between [[...]] or [(...)] are considered inlined expressions in Thymeleaf, and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

Note that, while [[...]] corresponds to th:text (ie result will be HTML-escaped), [(...)] corresponds to th:utext and will not perform any HTML-escaping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM