跳转到主要内容

thymeleaf模版中 th:if 属性不生效的一种情况

Avatar emanjusaka
统计中…
303
0
thymeleaf模版中 th:if 属性不生效的一种情况

作者:毅念安(Inian / Emanjusaka)|原创,后续会更新修正,转载请保留原文链接。
📝 独立博客:https://www.emanjusaka.com|博客园:https://www.cnblogs.com/emanjusaka|公众号:毅念安

当属性th:if和th:replace一起使用时会导致th:if没有效果

例如下面这种错误的用法

 <th:block th:if="${_templateId == 'post'}" th:replace="~{modules/widgets/toc}"></th:block>

上面的问题在于 th:replace 的执行时机。

在 Thymeleaf 的处理流程中,th:replace 是在模板解析阶段执行的,而 th:if 是在渲染阶段执行的。

这意味着,即使 th:if 的条件为 false,th:replace 也可能已经在之前执行了替换操作。

在 Thymeleaf 中,如果你想要根据条件来决定是否替换某个部分,你应该将 th:if 放在被替换的片段内部,而不是放在包含 th:replace 的元素上。这样,只有当条件满足时,被替换的片段才会被渲染和包含进来。

可以这样修改代码:

 <!-- 在原始模板中 -->
 <th:block th:replace="~{modules/widgets/toc}"></th:block>
 <!-- 在 modules/widgets/toc.html 文件中定义一个名为 tocBlock 的片段 -->
     <th:block th:if="${templateId == 'post'}">
         <!-- 这里放置只有在 _templateId 为 'post' 时才显示的内容 -->
         <p>这是只有在模板ID为post时显示的段落。</p>
     </th:block>
 ​


本文由 emanjusaka 创作,发表于 www.emanjusaka.com,采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

❋

微信扫码分享

微博
点赞是美意,赞赏是鼓励。如有帮助,可以关注下微信公众号。
微信 微信
支付宝 支付宝
查看赞赏名单 →
评论
← 上一篇 GitHub Actions上传打包缺失.vite/mainfest.json文件 下一篇 → 引入 Spring AI 依赖报错Could not find artifact org.springframework.ai...