[英]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 ' < > &
more text
因為我正在處理純文本而不是 HTML 或 XML,所以它不應該打印未轉義的特殊字符嗎?
我已將模式設置為 TEXT 並將編碼設置為 UTF-8。
請賜教。
謝謝
缺口
您應該使用[(${myVar})]
來打印未轉義的文本。
(我同意[[${...}]]
表達式在 TEXT 模板模式下轉義 HTML 特殊字符很奇怪。)
從以下位置更改您的模板:
free text
[[${myVar}]]
more text
...到:
free text
[(${myVar})]
more text
[[...]]
或[(...)]
之間的表達式在 Thymeleaf 中被視為內聯表達式,在它們內部我們可以使用任何類型的表達式,這些表達式在th:text
或th:utext
屬性中也有效。請注意,雖然
[[...]]
對應於th:text
(即結果將被 HTML 轉義),而[(...)]
對應於th:utext
並且不會執行任何 HTML 轉義
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.