如何在Velocity foreach循环中获得从零开始的计数 [英] How to get a zero-based count in a Velocity foreach loop

查看:1682
本文介绍了如何在Velocity foreach循环中获得从零开始的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



if i使用:

$ p $ #foreach($ list中的$ item)
item.getName():$ velocityCount
#end

我会得到:

<$ pre $



$ $ $ $ $ $ $ $

但是我需要:

  Fred:0 
Wilma:1
Barney: 2

从速度模板的角度来看,解决方案必须尽可能简单。



编辑

我可以使用:

 $ 
$($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
#end

但我正在寻找一个更优雅的解决方案。



编辑2

我需要基于one反备也可用。也就是说,在同一个模板中,我很可能会有一个 #foreach 指令,它需要一个基于零的计数器,而另一个 #foreach c> $ foreach.index (从0开始)和 $ foreach.count (从1开始)在循环内可用的特殊变量。



$ velocityCount 是很久以前afaik弃用的东西。


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.

解决方案

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.

这篇关于如何在Velocity foreach循环中获得从零开始的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆