如何使用 Thymeleaf 动态设置 HTML 元素的 id 属性

How to set the id attribute of HTML element dynamically with Thymeleaf

假设我有一个对象:${object}

我有以下表格:

<form id="{{'myForm' + object.id}" class="some class"
      th:action="@{/doSomething}" method="post">
    ....
</form>

如果我们假设 object.id 为“1”,我的目标是设置 id = "myForm1"。

PS:我写它的方式适用于 Angular JS。

您必须使用 th:id 属性:

<form th:id="'myForm' + ${object.id}" class="some class" th:action="@{/doSomething}" method="post">
// *** Other code here ***
</form>

以下是如何将动态 ID 与标签一起使用:

        <th:block th:with="randomId=${#strings.randomAlphanumeric(10)}">
            <input type="checkbox" th:id="${randomId}">
            <label th:for="${randomId}"></label>
        </th:block>

还有另一种(不错的)方法可以做到这一点。

假设您正在迭代一个项目列表,如下所示,您可以使用以下 th:id 使用被迭代项目的索引设置 id。

<th:block th:each="item : ${list}">
  <div class="tab-pane active" th:id="@{|#div-id-${itemStat.count}|}"></div>
</th:block>

此示例在 <div> 上设置一个 id。请注意 itemStat 是给定迭代器名称的固定名称 item.