Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL Count the ForEach loop

I am trying to print some message for every 4 items in the List of items

<c:forEach items="${categoryList}" var="category" varStatus="i">
    <c:if test="${i%4 == 0}">
        <c:out value="Test" />
    </c:if>
    <div class="span3">
        <c:out value="a" />
    </div>
</c:forEach>

But I am getting below exceptions, seems like i is not treated as number

java.lang.IllegalArgumentException: Cannot convert javax.servlet.jsp.jstl.core.LoopTagSupport$1Status@3371b822 of type class javax.servlet.jsp.jstl.core.LoopTagSupport$1Status to Number
    at org.apache.el.lang.ELArithmetic.coerce(ELArithmetic.java:407)
    at org.apache.el.lang.ELArithmetic.mod(ELArithmetic.java:291)
    at org.apache.el.parser.AstMod.getValue(AstMod.java:41)
    at org.apache.el.parser.AstEqual.getValue(AstEqual.java:38)

How do I achieve this?

One way is to declare a variable and increment for every loop with the help of scriplets. But I would like to avoid this!

like image 267
RaceBase Avatar asked Feb 06 '14 09:02

RaceBase


People also ask

What is varStatus Jstl?

The varStatus variables give the user the means to refer to: the first row/node returned by a ForEach Tag; the last row/node returned by a ForEach Tag; the count of the current row/node returned by a ForEach Tag; and the index of the current row/node returned by a ForEach Tag.

What is the syntax for ForEach loop in JSTL?

JSTL - Core <c:forEach>, <c:forTokens> Tag The <c:forEach> tag is a commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens.

Which JSTL tags would you use to iterate over a collection of XML objects?

JSTL - XML <x:forEach> Tag The <x:forEach> tag is used to loop over nodes in an XML document.


2 Answers

The variable i is of type LoopTagStatus. To get an int, you can use getCount() or getIndex().

If you want to print message for 1st item, then use:

<!-- `${i.index}` starts counting at 0 -->
<c:if test="${i.index % 4 == 0}">  
    <c:out value="Test" />
</c:if>

else use:

<!-- `${i.count}` starts counting at 1 -->
<c:if test="${i.count % 4 == 0}">
    <c:out value="Test" />
</c:if>
like image 152
Rohit Jain Avatar answered Sep 30 '22 09:09

Rohit Jain


varStatus is of the type LoopTagStatus (JavaDoc). So you have to use the property count of i:

<c:if test="${i.count % 4 == 0}">
    <c:out value="Test" />
</c:if>
like image 38
user1983983 Avatar answered Sep 30 '22 08:09

user1983983