Search code examples
jspjstljsp-tags

Foreach loop in a jsp page - Ending and Continuing a List


I just wanted to know how can I end a list of items in a particular column and continue the remaining items in a separate column. For instance: In the first column, there are rows having the value of "item1", "item2", "item3" and in the second column as a continuation, there are values "item4", "item5", "item6".

Actually, I want to have 4 columns having 5 items for each continuously. How can I apply this on the code below using a foreach loop in a jsp page?

<table>
    <c:forEach items="${itemList}" var="item"> 
        <tr>
            <td><input type ="submit" class="Items btnColor" 
                       value="${item.itemName}" label ="${item.itemId}" />
            </td>
        </tr>
    </c:forEach>
</table>    

Please help, thank you very much!


Solution

  • You can use varStatus variable to determine the index of your loop and using an if condition skip that iteration like:

    Suppose your table has 5 columns and you have to skip 3rd column then

    <c:set value="2" var="firstIndex" />    // this is the columnIndex which is not required
    <c:set value="5" var="splitColumn" />   // thi is the total length of arraylist
        <table>
            <c:forEach items="${itemList}" var="item" varStatus="itemLoop">
               <c:if test="${not (itemLoop.count eq firstIndex)}"> // this condition will skip the third column elements indexes from your arraylist.
                 <c:set value="${firstVal+5}" var="firstIndex" /> // this is increment in you arraylist index for all values ocurring at 3rd column
                 <c:if test="${(itemLoop.count eq splitColumn)}"> // this condition will create a row element after every 5 elements read from array list.
                   <tr>
                 </c:if>
                    <td><input type ="submit" class="Items btnColor" 
                               value="${item.itemName}" label ="${item.itemId}" />
                    </td>
                  <c:if test="${(itemLoop.count eq splitColumn)}"> // increment for the no of rows to split after very 5 elements
                    <c:set value=${splitColumn+5} var="splitColumn" />
                    </tr>
                  <c:if/>
              </c:if>
            </c:forEach>
        </table>