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

Spring Boot 3.0.1+Thymeleaf3.1中单引号内双引号转义求助

解决Thymeleaf 3.1片段参数中HTML标签的引号转义问题

方案1:使用Thymeleaf文本块语法(推荐)

Thymeleaf 3+支持|...|文本块语法,无需手动转义引号,直接编写HTML内容即可:

<a th:replace="~{fragments/paging :: paging(${totalPages}, |<i class='fa-solid fa-forward-step'></i>|, 'Last Page')}"></a>

若习惯用双引号定义class属性,也可直接写入文本块,Thymeleaf会自动处理边界冲突:

<a th:replace="~{fragments/paging :: paging(${totalPages}, |<i class=\"fa-solid fa-forward-step\"></i>|, 'Last Page')}"></a>

方案2:提前定义变量传递

在页面顶部用th:with定义图标变量,再将变量传入片段,避免直接在参数中编写复杂HTML:

<div th:with="lastIcon='<i class=&quot;fa-solid fa-forward-step&quot;</i>'"></div>
<a th:replace="~{fragments/paging :: paging(${totalPages}, ${lastIcon}, 'Last Page')}"></a>

这里变量值用单引号包裹,内部双引号通过&quot;转义,Thymeleaf会正确解析为HTML属性的引号。

方案3:强制不转义表达式

使用__${...}__语法告诉Thymeleaf不对内容进行HTML转义,直接输出原始HTML:

<a th:replace="~{fragments/paging :: paging(${totalPages}, __'<i class=&quot;fa-solid fa-forward-step&quot;</i>', 'Last Page')}"></a>

关键注意事项

若之前出现“内容原样显示”的问题,大概率是因为片段fragments/paging :: paging中用了th:text渲染参数,需改为th:utext才能正确解析HTML标签:

<!-- 片段内部正确写法 -->
<span th:utext="${你的图标参数名}"></span>

内容的提问来源于stack exchange,提问作者Ajay Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:45:26