java 如何在 Velocity foreach 循环中获得从零开始的计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7847432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:40:45  来源:igfitidea点击:

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

javaforeachvelocity

提问by summerbulb

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

我试图在 Velocity#foreach指令中获得一个从零开始的计数器。

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 #foreachdirective that will require a zero-based counter and another #foreachdirective that requires a one-base counter.

编辑 2
我也需要基于一个的计数器可用。也就是说,在同一个模板中,我很可能有一个#foreach指令需要一个从零开始的计数器,另一个#foreach指令需要一个从零开始的计数器。

回答by serg

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

如果您使用的是 Velocity 1.7,则循环内有$foreach.index(基于 0 的)和$foreach.count(基于 1 的)特殊变量可用。

$velocityCountis something that was deprecated long time ago afaik.

$velocityCount很久以前就被弃用了 afaik。

回答by Dhiral Pandya

#set($i = 0)

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

回答by alun

According to the doc, you can specify:

根据doc,您可以指定:

directive.foreach.counter.initial.value = 0

In velocity.properties file.

在velocity.properties 文件中。

回答by Dave Newton

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 #forEachZeroBasedand #forEachOneBased.

好吧,很明显,您不能同时拥有两者——您要么只需要在显示时进行数学计算,要么创建一个自定义指令这是 SO 帖子链接到的文章)。例如,您可以拥有#forEachZeroBased#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.

自定义指令有时非常有用,尽管 IMO 这不是其中之一——只是做数学计算,这是显而易见的解决方案,而且没什么大不了的。