如何避免Thymeleaf属性值中的引号被转义?
Thymeleaf生成单引号包裹JSON的data属性并支持离线预览
需求
需要生成如下HTML页面:
<html> <body> <my-webcomponent data='{"foo":"bar"}'></my-webcomponent> </body> </html>
核心要求:
- 动态修改
data属性内的JSON字符串,用单引号包裹属性值,避免双引号被转义为" - 模板支持离线预览:保留静态示例的
data属性,同时通过Thymeleaf的th:属性实现动态替换
尝试过的写法(无效)
使用th:data直接绑定变量,但Thymeleaf仍会自动转义引号:
<my-webcomponent th:data='${jsonData}' data='{"foo":"bar"}'></my-webcomponent>
补充示例代码
Spring Boot控制器代码
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class Demo { record FooBar(String foo) {} @GetMapping(value = "/demo", produces = "text/html") public final String enter(Model model) throws JsonProcessingException { FooBar fooBar = new FooBar("bar"); ObjectMapper mapper = new ObjectMapper(); String foobarAsString = mapper.writer().writeValueAsString(fooBar); model.addAttribute("foobar", foobarAsString); return "demo.html"; } }
原始HTML模板(输出带转义引号)
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <body> <my-custom-tag th:data="${foobar}"> </my-custom-tag> </body> </html>
服务器返回结果(curl输出)
$ curl http://localhost:8080/demo <html lang="en"> <body> <my-custom-tag data="{"foo":"bar"}"> </my-custom-tag> </body> </html>
解决方案
使用Thymeleaf的th:attr属性配合非转义内联表达式,同时保留静态data属性:
修改后的HTML模板
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <body> <my-custom-tag th:attr="data='[(${foobar})]'" data='{"foo":"bar"}'> </my-custom-tag> </body> </html>
原理说明
[(${foobar})]是Thymeleaf的非转义内联表达式,会直接输出变量的原始字符串内容,不进行HTML转义- 用单引号包裹整个表达式结果,最终生成的
data属性值会以单引号包裹JSON,避免双引号被转义 - 静态
data='{"foo":"bar"}'会在离线预览时生效,浏览器会忽略th:开头的属性,满足离线预览需求
最终服务器返回结果
$ curl http://localhost:8080/demo <html lang="en"> <body> <my-custom-tag data='{"foo":"bar"}'> </my-custom-tag> </body> </html>
内容的提问来源于stack exchange,提问作者somebody
相关产品推荐
相关产品推荐

