How to set the id attribute of HTML element dynamically with Thymeleaf
There is still another (nice) way to accomplish this.
Assuming you are iterating a list of items as shown below, you can use the following th:id
to set the id using the index of the item being iterated.
<th:block th:each="item : ${list}">
<div class="tab-pane active" th:id="@{|#div-id-${itemStat.count}|}"></div>
</th:block>
This example sets an id on a <div>
. Note that itemStat
is a fixed name given the iterator name as item
.
You have to use th:id attribute:
<form th:id="'myForm' + ${object.id}" class="some class" th:action="@{/doSomething}" method="post">
// *** Other code here ***
</form>
Here is how you can use dynamic id with label:
<th:block th:with="randomId=${#strings.randomAlphanumeric(10)}">
<input type="checkbox" th:id="${randomId}">
<label th:for="${randomId}"></label>
</th:block>