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

前端 未结 4 1127
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 02:20

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

if i use:

#foreach ($item in $list)
   item.getName() : $veloc         


        
相关标签:
4条回答
  • 2021-01-04 02:43

    According to the doc, you can specify:

    directive.foreach.counter.initial.value = 0
    

    In velocity.properties file.

    0 讨论(0)
  • 2021-01-04 03:05
    #set($i = 0)
    
      #foreach($str in $names)
        #set($i = $i+1)
        $i : $str
     #end
    
    0 讨论(0)
  • 2021-01-04 03:10

    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.

    0 讨论(0)
  • 2021-01-04 03:10

    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.

    0 讨论(0)
提交回复
热议问题