Rey Libutan
Rey Libutan

Reputation: 5314

Thymeleaf: Iteration - increment by N and access list.get(N)

So I've read the Iterations part of the documentation already but still didn't give any idea on how to do the following:

Iterate per 2 records (since I am rendering something like below) and access list by index.

<div class="row">
   <div class="col-md-6">
      ...
   </div>
   <div class="col-md-6">
      ...
   </div>
</div>

Basically if this were in code, it looks something like

for (int i = 0; i < size;) {
    // do stuff

    // manual increment
    if (i + 2 > size) {
        i++;
    } else {
        i += 2;
    }
}

Any other approach that would satisfy my problem is always welcome too!

Upvotes: 0

Views: 4557

Answers (1)

Rey Libutan
Rey Libutan

Reputation: 5314

I was able to solve it using something like below:

Basically, I still loop individually but just skip every other record using th:if="${stat.even}" and just get the next record by stat.index + 1.

Be really cautious about the IndexOutOfBoundsException though.

<div class="row" th:each="hivRisk, stat : ${hivRiskList}" th:if="${stat.even}">
   <div class="col-md-6" th:with="leftRisk=${hivRiskList.get(stat.index)}">
      <div class="checkbox checkbox-styled">
         <label>
         <input type="checkbox" value="-1" th:value="${leftRisk.id}"/>
         <span th:text="${leftRisk.name}">HIV Risk</span>
         </label>
      </div>
   </div>
   <div class="col-md-6" th:if="${stat.index + 1 &lt; hivRiskList.size()}" th:with="rightRisk=${hivRiskList.get(stat.index + 1)}">
      <div class="checkbox checkbox-styled">
         <label>
         <input type="checkbox" value="-1" th:value="${rightRisk.id}"/>
         <span th:text="${rightRisk.name}">HIV Risk</span>
         </label>
      </div>
   </div>
</div>

Upvotes: 1

Related Questions