使用 Java 避免在 Thymeleaf 中转义特殊字符

Avoid special character escaping in Thymeleaf with Java

我正在尝试使用 Thymelead 作为我拥有的一些文本模板的模板引擎。

我的模板是这样的

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

我的Java代码是

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

我期待上面的打印

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

而是打印

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

既然我正在处理纯文本而不是 HTML 或 XML,它不应该打印未转义的特殊字符吗?

我已将模式设置为文本并将编码设置为 UTF-8。

请赐教

谢谢

尼克

您应该使用 [(${myVar})] 打印未转义的文本。

(我同意 [[${...}]] 表达式在 TEXT 模板模式下转义 HTML 特殊字符很奇怪。)

更改您的模板:

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

...至:

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

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 (i.e. result will be HTML-escaped), [(...)] corresponds to th:utext and will not perform any HTML-escaping