簡體   English   中英

避免使用 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,所以它不應該打印未轉義的特殊字符嗎?

我已將模式設置為 TEXT 並將編碼設置為 UTF-8。

請賜教。

謝謝

缺口

您應該使用[(${myVar})]來打印未轉義的文本。

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

從以下位置更改您的模板:

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

...到:

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

正如Thymealeaf 的文檔中所述

[[...]][(...)]之間的表達式在 Thymeleaf 中被視為內聯表達式,在它們內部我們可以使用任何類型的表達式,這些表達式在th:textth:utext屬性中也有效。

請注意,雖然[[...]]對應於th:text (即結果將被 HTML 轉義),而[(...)]對應於th:utext並且不會執行任何 HTML 轉義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM