ssgtob1
ssgtob1

Reputation: 107

JSTL For Each multiple items for each iteration

I am trying to write out a table using JSTL c:forEach and cant seem to get my head wrapped around it. I have one set of items (a single dimension list) and need to make a table like so:

<table>
 <th>         <th>        <th>        <th>       <th>
 listItem[0] listItem[1] listItem[2] listItem[3] listItem[4] 
 listItem[5] listItem[6] listItem[7] listItem[8] listItem[9]

and so on. Length of listItem is not known and will vary. Any help would be greatly appreciated.

Upvotes: 1

Views: 1755

Answers (2)

rickz
rickz

Reputation: 4474

Here is a complete example.

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<c:set var="myList" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23"/>
<html>
    <body>
        <table>
            <c:forEach items="${myList}" var="current" varStatus="status">
                <c:if test="${status.count % 5 == 1}"><tr></c:if>
                    <td>${current}</td>
                <c:if test="${status.count % 5 == 0}"></tr></c:if>
            </c:forEach>
        </table>
    </body>
</html>

Upvotes: 2

obourgain
obourgain

Reputation: 9336

You can iterate over your table every five values, and print five values at each iteration.

For example:

<c:forEach items="${table}" var="item" step="5" varStatus="i">
     ${table[i.index]} 
     ${table[i.index+1]} 
     ${table[i.index+2]} 
     ${table[i.index+3]} 
     ${table[i.index+4]}<br />
</c:forEach>

Upvotes: 2

Related Questions