[英]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.