How to use a var counter in Thymeleaf?

Asked

Viewed 181 times

0

Can I create a counter variable in Thymeleaf? I need an incremental variable to pass as a tag ID in HTML. I have the following loops, where each loop will be iterated x different times, so I can’t use the index of any loops to define the id of the tags that should be sequential (value0, value1, value2...).

<div class="col m12">
   <div th:each="e, index : ${produto.etapasTrabalho}">
      <div th:each="t : ${e.tarefas}">
         <div th:each="i : ${t.itensTarefa}">
            <div id="campo" class="campo input-field col m8" th:if="${i.tipo.toString() == 'Data'}">
               <input type="text" id="id" th:value="${i.id}" th:hidden="hidden" />
               <label th:text="${i.nome}"></label>
               <input type="text" th:value="${i.valor}" class="datepicker" th:id="'valor'+${index}" />
            </div>
            <div id="campo" class="campo input-field col m8" th:if="${i.tipo.toString() == 'Texto'}">
               <input type="text" id="id" th:value="${i.id}" th:hidden="hidden" />
               <input type="text" th:id="'valor'+${index}" th:value="${i.valor}" />
               <label th:text="${i.nome}"></label>
            </div>
            <div id="campo" class="campo input-field col m8" th:if="${i.tipo.toString() == 'Texto Longo'}">
               <input type="text" id="id" th:value="${i.id}" th:hidden="hidden" />
               <textarea class="materialize-textarea" th:value="${i.valor}" th:id="'valor'+${index}"></textarea>
               <label th:text="${i.nome}"></label>
            </div>
            <div id="campo" class="campo input-field col m8" th:if="${i.tipo.toString() == 'Dinheiro $'}">
               <input type="text" id="id" th:value="${i.id}" th:hidden="hidden" />
               <input class="money" type="text" th:value="${i.valor}" th:id="'valor'+${index}" />
               <label th:text="${i.nome}"></label>
            </div>
            <div id="campo" class="campo" th:if="${i.tipo.toString() == 'Check'}">
               <input type="text" id="id" th:value="${i.id}" th:hidden="hidden" />
               <input type="checkbox" class="filled-in" id="check" th:id="'valor'+${index}" />
               <label for="check" th:text="${i.nome}"></label>
            </div>
         </div>
      </div>
      <br/>
   </div>
</div>

If not possible, I can use a javascript variable?

1 answer

0


I found the solution through javascript, I simply search all fields contain a certain class and define the element id attribute with each index.

$('.campo').each(function(i) {
       $(this).attr('id', 'valor' + i);
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.