How to get a zero-based count in a Velocity foreach loop

22,202

Solution 1

If you are using Velocity 1.7 there are $foreach.index (0-based) and $foreach.count (1-based) special vars available inside loops.

$velocityCount is something that was deprecated long time ago afaik.

Solution 2

#set($i = 0)

  #foreach($str in $names)
    #set($i = $i+1)
    $i : $str
 #end

Solution 3

Well, you can't have both, obviously--you either need to just do the math when you're displaying, or create a custom directive (and here's the article the SO post links to). For instance, you could have #forEachZeroBased and #forEachOneBased.

Custom directives are very useful sometimes, although IMO this isn't one of them--just do the math, it's the obvious solution, and it's just not that big of a deal.

Solution 4

According to the doc, you can specify:

directive.foreach.counter.initial.value = 0

In velocity.properties file.

Share:
22,202
summerbulb
Author by

summerbulb

Updated on July 27, 2020

Comments

  • summerbulb
    summerbulb almost 4 years

    I am trying to get a zero-based counter in a Velocity #foreach directive.

    if i use:

    #foreach ($item in $list)
       item.getName() : $velocityCount
    #end
    

    i will get:

    Fred : 1
    Wilma : 2
    Barney : 3
    

    But i need:

    Fred : 0
    Wilma : 1
    Barney : 2
    

    The solution must be as simple as possible from the velocity template's point of view.

    EDIT:
    I can use:

    #foreach ($item in $list)
       #set( $num = $velocityCount - 1 ) //The white space in mandatory
       item.getName() : $num
    #end
    

    and it works. But I'm looking for a more elegant solution.

    EDIT 2:
    I need the one-based counter to be available too. That is, in the same template i will most likely have one #foreach directive that will require a zero-based counter and another #foreach directive that requires a one-base counter.

  • summerbulb
    summerbulb over 12 years
    Thanks, but that will deprive me from the ability to use the one-based counter. See edit2.
  • Dave Newton
    Dave Newton over 12 years
    Good point, I had assumed < 1.7 because of the velocityCount reference--bad assumption!
  • Dave Newton
    Dave Newton over 12 years
    @summerbulb Obviously I did, since I commented on it and voted it up-like I said, I assumed < 1.7 since the index/count thing is documented in the user guide.