12.4.1. Foreach 循环

#foreach 元素允许进行循环,例如:

  1. <ul>
  2. #foreach( $product in $allProducts )
  3. <li>$product</li>
  4. #end
  5. </ul>

这个#foreach 循环将导致$allProducts 列表 (对象) 为查询所有的产品$products (目标)遍历一遍。每次经过循环,从$allProducts取得的值将置于$product 变量之中。

$allProducts 变量的内容是一个矢量,一个哈希表或者数组。赋给$product 变量的值是一个Java 对象并且可以从一个类似的变量引用。例如,如果 $product 真是一个Java的产品类,其名称可以通过引用$product.Name 方法来检索(即: $Product.getName())。

我们假定 $allProducts 是一个哈希表。如果你想检索关键字的值或者在哈希表中的对象,你可以使用以下的代码:

  1. <ul>
  2. #foreach( $key in $allProducts.keySet() )
  3. <li>Key: $key -> Value: $allProducts.get($key)</li>
  4. #end
  5. </ul>

Velocity 提供一个更容易的方式或的循环计数,以便你可以做下面类似的工作:

  1. <table>
  2. #foreach( $customer in $customerList )
  3. <tr><td>$velocityCount</td><td>$customer.Name</td></tr>
  4. #end
  5. </table>

循环计数变量的缺省名称是$velocityCount,在velocity.properties 配置文件中标明。默认情况下,该变量从1开始计数,但是可以在velocity.properties 文件中设为从0或者1开始。下面是velocity.properties 文件中循环变量设置一节:

  1. # Default name of the loop counter
  2. # variable reference.
  3. directive.foreach.counter.name = velocityCount
  4. # Default starting value of the loop
  5. # counter variable reference.
  6. directive.foreach.counter.initial.value = 1