Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JSTL forEach loop's varStatus as an ID

Tags:

java

jsp

jstl

el

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" >
like image 729
Mark W Avatar asked Jul 06 '11 17:07

Mark W


People also ask

What is varStatus in forEach of JSTL?

varStatus is what you want! You declare a new variable within the main forEach JSP block which will allow you to access the internal loop counter of the for-each loop. Then you can call a number of methods on that object to be able to do conditional processing.

What is the syntax for forEach loop in JSTL?

The <c:for each > is an iteration tag used for repeating the nested body content for fixed number of times or over the collection. These tag used as a good alternative for embedding a Java while, do-while, or for loop via a scriptlet.


2 Answers

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
like image 146
highlycaffeinated Avatar answered Oct 13 '22 08:10

highlycaffeinated


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

like image 10
diego matos - keke Avatar answered Oct 13 '22 09:10

diego matos - keke