Spring Boot与Thymeleaf嵌套th:block报错,求替代方案
问题解决:Thymeleaf嵌套th:block报错的真实原因及修复
首先明确:Thymeleaf完全支持嵌套th:block,你遇到的报错不是因为嵌套导致的,而是代码里的HTML语法错误——看这段代码:
<td th:rowspan="${record.size()} th:if="${iterStat.first}">Attribute : </td>
这里的th:rowspan属性没有闭合引号,应该写成th:rowspan="${record.size()}",缺失的闭合引号让Thymeleaf解析器混乱,才抛出了错误提示。
修正后的完整代码
<th:block th:each="claim:${claimEditor}"> <table> <tr> <td>Number of claim : </td> <td th:text="${claim.numberOfClaim}"></td> </tr> <th:block th:unless="${#lists.isEmpty(claim.record)}"> <th:block th:each="record, iterStat:${claim.record}"> <tr> <td th:rowspan="${record.size()}" th:if="${iterStat.first}">Attribute : </td> <td th:text="${record}"></td> </tr> </th:block> </th:block> </table> </th:block>
可选简化方案(非必须,仅优化层级)
如果想减少嵌套层级,也可以把th:unless和th:each合并到同一个th:block上,代码会更简洁:
<th:block th:each="claim:${claimEditor}"> <table> <tr> <td>Number of claim : </td> <td th:text="${claim.numberOfClaim}"></td> </tr> <th:block th:unless="${#lists.isEmpty(claim.record)}" th:each="record, iterStat:${claim.record}"> <tr> <td th:rowspan="${record.size()}" th:if="${iterStat.first}">Attribute : </td> <td th:text="${record}"></td> </tr> </th:block> </table> </th:block>
内容的提问来源于stack exchange,提问作者robert trudel
相关产品推荐
相关产品推荐

