Tutorial :How to show a group of 3 elements of a collection using JSTL in JSP?



Question:

I have a list of n elements that I want to output in a group of 3. The size of the collection can vary a lot, but the output must be grouped in 3.

<ul>     <li>        <div>element 1</div>        <div>element 2</div>        <div>element 3</div>     </li>       <li>        <div>element 4</div>        <div>element 5</div>        <div>element 6</div>     </li>       <li>        <div>element 7</div>        <div>element 8</div>     </li>   </ul>  

I would like to use a forEach and a if statement, but I cannot get the output to generate properly. Any suggestions?


Solution:1

I'm not sure about the syntax, but this should help, using the "count" property of "varStatus" to know what element number you are on...

EDIT: Apparently ".count" is NOT zero indexed, so the correct code would be:

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>  <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>    ...  <c:set var="myListSize" value="${fn:length(myList)}"/>            <c:forEach var="element" items="${myList}" varStatus="stat">                <c:choose>                    <c:when test="${ stat.count == 1 }">                     <ul>                     <li>                        <div>${element}</div>                  </c:when>                    <c:when test="${ stat.count == myListSize }">                        <div>${element}</div>                     </li>                     </ul>                  </c:when>                    <c:when test="${stat.count % 3 == 0 && stat.count < myListSize }">                        <div>${element}</div>                     </li>                     <br/>                     <li>                  </c:when>                    <c:otherwise>                        <div>${element}</div>                  </c:otherwise>                </c:choose>            </c:forEach>  

It can still be improved, but for now it works.


Solution:2

This may not be optimal, but how about just doing one pass in Java scriptlet, creating groups of 3s, adding them to a bean, and then iterating over those with 2 nested foreach loops.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »