110

I want to use the count from the JSTL forEach loop, but my code doesnt seem to work.

<c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount}">
    </div>
</c:forEach>

produces

<div id="divIDNojavax.servlet.jsp.jstl.core.LoopTagSupport$1Status@5570e2" >
Mark W
  • 5,824
  • 15
  • 59
  • 97
  • 9
    Here is the class' javadoc: http://download.oracle.com/javaee/6/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html Look what getter methods it offers. Yes, among others there's a `getIndex()` :) – BalusC Jul 06 '11 at 17:51

4 Answers4

267

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
  • 23
    `${theCount.count}` **always** starts at 1. `${theCount.index}` starts at whatever you have set the `begin` attribute to. e.g. `` – vegemite4me Aug 22 '13 at 09:23
10

you'd use any of these:

JSTL c:forEach varStatus properties

Property Getter Description

  • current getCurrent() The item (from the collection) for the current round of iteration.

  • index getIndex() The zero-based index for the current round of iteration.

  • count getCount() The one-based count for the current round of iteration

  • first isFirst() Flag indicating whether the current round is the first pass through the iteration
  • last isLast() Flag indicating whether the current round is the last pass through the iteration

  • begin getBegin() The value of the begin attribute

  • end getEnd() The value of the end attribute

  • step getStep() The value of the step attribute

diego matos - keke
  • 2,099
  • 1
  • 20
  • 11
6

You can try this. similar result

 <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount.count}"></div>
 </c:forEach>
Sanath
  • 4,774
  • 10
  • 51
  • 81
Nathanphan
  • 947
  • 2
  • 11
  • 23
1

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

jyoti pani
  • 11
  • 1
  • @HenryKeiter there is a real answer here. Bad formatting just had all the html hidden until I fixed it. – Dan Is Fiddling By Firelight Jul 15 '14 at 21:22
  • This provides the exact same answer as was already provided 3 years earlier (use `varStatus.count`), only much less readable. Why bother reading other people's answers? ;) – rustyx Mar 30 '15 at 20:18