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

如何通过HTMX动态传递ID至hx-put接口填充编辑表单?

解决HTMX动态传递行ID到PUT接口的问题

在Spring Boot后端+Thymeleaf+HTMX的项目中,需要在表格每行的编辑按钮上动态传递当前行的ID到PUT接口(类似/openai/model/3中的3),用来获取数据填充编辑表单。目前硬编码ID时功能正常,但尝试用hx-vals=js:{"id":${model.getId()}}动态绑定ID时失效,找不到可行的动态传递示例,需要解决办法。

原代码示例:

<tr th:each="model : ${models}">
    <th scope="col">
        <button type="button" title="Edit"
                class="btn btn-outline-primary"
                hx-put=/openai/model
                hx-vals=js:{"id":${model.getId()}}
                hx-target="body"
                hx-trigger="click">
            <i class="bi-pencil"></i>
        </button>
        <button type="button" title="Delete"
                class="btn btn-outline-danger">
            <i class="bi-trash"></i>
        </button>
    </th>
    <th scope="row" th:text="${model.getId()}"></th>
    <td th:text="${model.getModel()}"></td>
    <td th:text="${model.getPrice()}"></td>
    <td th:text="${model.getLimit()}"></td>
    <td th:text="${model.getCreatedAt()}"></td>
</tr>

问题原因

  1. 原hx-vals写法未正确结合Thymeleaf表达式与HTMX的JS语法,渲染后JS代码格式错误
  2. 若后端接口要求ID在URL路径中,hx-vals是将参数放在请求体,不符合路径参数的需求

解决方案

方法1:直接用Thymeleaf拼接URL路径(推荐)

这是最符合REST风格的方案,直接把ID拼在hx-put的URL里,无需额外处理参数:

修改后的按钮代码:

<button type="button" title="Edit"
        class="btn btn-outline-primary"
        hx-put="/openai/model/[[${model.getId()}]]"
        hx-target="body"
        hx-trigger="click">
    <i class="bi-pencil"></i>
</button>

或者用Thymeleaf的th:attr属性拼接:

<button type="button" title="Edit"
        class="btn btn-outline-primary"
        th:attr="hx-put='/openai/model/' + ${model.getId()}"
        hx-target="body"
        hx-trigger="click">
    <i class="bi-pencil"></i>
</button>

对应Spring Boot后端接口:

@PutMapping("/openai/model/{id}")
public String getEditForm(@PathVariable Long id, Model model) {
    // 根据ID查询数据
    ModelEntity modelData = modelService.getById(id);
    model.addAttribute("model", modelData);
    // 返回编辑表单片段
    return "fragments/edit-model-form";
}

方法2:修正hx-vals的正确写法(适用于ID放在请求体的场景)

如果后端接口需要从请求体接收ID,需确保Thymeleaf正确渲染JS对象:

<button type="button" title="Edit"
        class="btn btn-outline-primary"
        hx-put="/openai/model"
        hx-vals='js:{"id": [[${model.getId()}]]}'
        hx-target="body"
        hx-trigger="click">
    <i class="bi-pencil"></i>
</button>

注意:用单引号包裹hx-vals属性值,避免和内部双引号冲突;用Thymeleaf内联表达式[[${}]]确保ID值正确注入JS对象。

方法3:用data属性存储ID再通过JS获取(灵活方案)

给按钮添加data-id属性存储ID,再通过JS动态读取:

<button type="button" title="Edit"
        class="btn btn-outline-primary"
        hx-put="/openai/model"
        hx-vals='js:{id: this.getAttribute("data-id")}'
        data-id="${model.getId()}"
        hx-target="body"
        hx-trigger="click">
    <i class="bi-pencil"></i>
</button>

内容的提问来源于stack exchange,提问作者Natalya Volokhova

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:03:10