Search code examples
spring-boothtmxspring-thymeleaf

how to append variable inside the hx-delete?


I currently have a springboot app with thymeleaf, now I'm trying to use HTMX. Now in my table, each row has a delete button.

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

On hx-delete, it cant detect the ${training.id}. I tried this but still not working

hx-delete="|/delete/${training.id}|"


Solution

  • Normal HTML attributes do not have access to Thymeleaf bindings. To solve this we can use the default attribute processor.

    5.6 Setting the value of any attribute (default attribute processor)

    Thymeleaf offers a default attribute processor that allows us to set the value of any attribute, even if no specific th:* processor has been defined for it at the Standard Dialect.

    So something like:

    <span th:whatever="${user.name}">...</span>
    

    Will result in:

    <span whatever="John Apricot">...</span>
    

    To pass a dynamic URL we'll have to combine this with the URL rules.

    Resulting in the following code:

    <a th:hx-delete="@{/delete/{id}(id=${training.id})}"></a>
    

    Assuming training.id is 1, this should produce:

    <a hx-delete="/delete/1"></a>
    

    ps. Using delete in the path seems unnecessary, since the HTTP method already signifies the same. A more logical route would be DELETE /trainings/:id.

    <a th:hx-delete="@{/trainings/{id}(id=${training.id})}"></a>