Search code examples
spring-mvcthymeleaf

onclick thymeleaf dynamic url parameter


i'm a starter in Spring MVC and i make somes mistakes ... so i want to forge a dynamic URL with a button and Thymeleaf, but it doesn't works. I think about escape quote or similar, the ${key} is not correct in the evaluation ?

<tr th:each="key: ${serverBean.getServerB().keySet()}">
    <td>
        <span th:text="${serverBean.getServerB().get(key)}" />
    </td>
    <td align="center">
        <span th:text="${key}" />
    </td>
    <td th:if="${protoStatusBean.getStatus(key)}" bgcolor="lime" />
    <td th:unless="${protoStatusBean.getStatus(key)}" bgcolor="red"/>
    <td>
        <button th:onclick="window.location.href='/update?server=${key}'">
            <img src="./images/wrench.png" height="15" width="15">
        </button>
    </td>
</tr>

thanks for your help and patience


Solution

  • In general, you have to surround text literals with single quotes. For your example to work, it should look like this:

    th:onclick="'window.location.href=\'/update?server=' + ${key} + '\''"
    

    That being said, there are various other ways to get the string concatenation to work, depending on what you think looks best.

    th:onclick="|window.location.href='/update?server=${key}'|"
    th:onclick="${'window.location.href=''/update?server=' + key + ''''}"
    th:onclick="|window.location.href='@{/update(server=${key})}'|"