You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Thymeleaf属性值中的引号被转义?

Thymeleaf生成单引号包裹JSON的data属性并支持离线预览

需求

需要生成如下HTML页面:

<html>
  <body>
    <my-webcomponent data='{"foo":"bar"}'></my-webcomponent>
  </body>
</html>

核心要求:

  • 动态修改data属性内的JSON字符串,用单引号包裹属性值,避免双引号被转义为&quot;
  • 模板支持离线预览:保留静态示例的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="{&quot;foo&quot;:&quot;bar&quot;}"> </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>

原理说明

  1. [(${foobar})]是Thymeleaf的非转义内联表达式,会直接输出变量的原始字符串内容,不进行HTML转义
  2. 用单引号包裹整个表达式结果,最终生成的data属性值会以单引号包裹JSON,避免双引号被转义
  3. 静态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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 07:49:54