Skip to main content
Windward

How can I get a count, first, last or specify an index of a forEach loop?

Overview

How to get a count, first, last or specify an index of a forEach loop.

Resolution

In the forEach tag you can make use of special variables that start with ${varStatus_name.} (NOTE this is in ADDITION TO the normal forEach tag variable name)  in order to do some automation that would take 2-3 tags using the set tag to accomplish.

This is from the AutoTag Guide.

varStatus – optional. Returns index, first, last, count for the loop iteration. Can be used in other tags, including <wr:out value=…>, using ${name.*} as follows:

Example:   varStatus = LoopStatus

 

Then you can reference distinct values through this additional varStatus variable (LoopStatus) directly in your select of other tags.   An example for the tags listed below would be an OUT tag inside the forEach loop where you have defined the varStatus variable (LoopStatus).

 

${LoopStatus.index} - the index in the collection of the item returned. This is 0-based and identifies the underlying element regardless of begin and step. For example, if begin="3" then the first value of index will be 3.

IE, <wr:out select="${LoopStatus.index}"/> would return and print a value of "3" from the example above

 

${LoopStatus.count} - the number of elements returned so far. This is 1-based and only counts elements actually returned (unlike index which includes all elements including those not returned.)

IE, <wr:out select="${LoopStatus.count}"/> would return and print the current iteration the loop is currently on (starting at zero 0) from the example above

 

${LoopStatus.first} - returns true() if on the first element to be returned. Otherwise returns false().

IE, <wr:out select="${LoopStatus.first}"/> would return and print a value of "true" for the first iteration and then "false" for all other iterations from the example above

 

${LoopStatus.last} - returns true() if on the last element to be returned. Otherwise returns false().

IE, <wr:out select="${LoopStatus.last}"/> would return and print a value of "false" for the all iterations except the last and then "true" for the last iterations from the example above

 

You can test these concepts by using our Southwind.xml file for an XML connection or our MSSQL Microsoft SQL connection that we provide with our products.   Simply insert a forEach tag, make a selection of arbitrary data that has sub nodes or items (IE, Customers table or node) and then assign both var and varStatus variables values.    Use the varStatus variable as shown above to reference these special functions.

  • Was this article helpful?