JSTL Count ForEach Loop

I am trying to print some message for every 4 items in the item list

<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 get below exceptions, it seems that i not considered as a 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 an increment for each loop using scripts. But I would like to avoid this!

+6
source share
2 answers

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

If you want to print a message for 1 st use:

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

else:

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

varStatus is of type LoopTagStatus ( JavaDoc ). Therefore, you need to use the count i property:

 <c:if test="${i.count % 4 == 0}"> <c:out value="Test" /> </c:if> 
+2
source

All Articles