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

如何在HTMX的hx-delete属性中拼接Thymeleaf变量?

解决方案

问题出在Thymeleaf对自定义属性的解析规则上——原生HTML属性(包括hx-delete这类第三方库属性)里的表达式不会被Thymeleaf自动处理,你需要给自定义属性加上th:前缀,让Thymeleaf识别并解析其中的变量。

直接用以下两种写法之一即可解决:

写法一:使用Thymeleaf URL表达式(推荐)

这种方式更符合Thymeleaf的URL规范,能自动处理上下文路径:

<tr th:each="training : ${trainings}">
    <th scope="row">[[${training.id}]]</th>
    <td>
        <a class="btn-delete" th:hx-delete="@{/delete/{id}(id=${training.id})}">删除</a>
    </td>
</tr>

写法二:使用字符串拼接表达式

如果习惯用字符串拼接的方式,也可以用+连接变量:

<tr th:each="training : ${trainings}">
    <th scope="row">[[${training.id}]]</th>
    <td>
        <a class="btn-delete" th:hx-delete="'/delete/' + ${training.id}">删除</a>
    </td>
</tr>

为什么之前的写法无效?

  • 直接写hx-delete="/delete/${training.id}":Thymeleaf不会解析原生属性里的${training.id},浏览器只会拿到带变量名的原始字符串。
  • 使用|/delete/${training.id}|:这种内联文本语法仅在标签内容中生效(比如<td>|/delete/${training.id}|</td>),在属性中不生效,必须通过th:前缀的属性结合表达式语法才能解析变量。

内容的提问来源于stack exchange,提问作者azer-p

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:07:05