(3)循环:foreach
下面是一个例子:
#foreach( $product in $allProducts )
- $product
#end
$allProducts的内容可以是Vector、Hashtable或ArrayList,每次取出一个值赋值给$product;返回的值是一个Java对象,可以用来引用具体的方法。下面的例子假设$allProducts是Hashtable对象:
#foreach( $key in $allProducts.keySet() )
- Key: $key -> Value: $allProducts.get($key)
#end
Velocity提供了访问循环计数变量的简单方法:
$velocityCount | $customer.Name |
$velocityCount是Velocity表示循环计数的内部变量,缺省开始值为1。该设置在velocity.properties文件中定义:
# Default name of the loop counter
# variable reference.
directive.foreach.counter.name = velocityCount
# Default starting value of the loop
# counter variable reference.
directive.foreach.counter.initial.value = 1
可以在#foreach指令中使用范围操作符[n..m],其中n和m必须是整型:
First example:
#foreach( $foo in [1..5] )
$foo
#end
Second example:
#foreach( $bar in [2..-2] )
$bar
#end
Third example:
#set( $arr = [0..1] )
#foreach( $i in $arr )
$i
#end
输出结果是:
First example:
1 2 3 4 5
Second example:
2 1 0 -1 -2
Third example:
0 1
(4)#include
#include指令导入本地文件到#include指令定义的地方。导入的文件内容不会被模板引擎解析。出于安全考虑,导入的文件应该放在TEMPLATE_ROOT目录下。一次可以导入多个文件,文件名之间用逗号分隔;并且通常使用变量引用来替代文件名。下面是一个例子:
#include( "greetings.txt", $seasonalstock )
(5)#parse
#parse指令允许导入一个包含VTL的本地文件,并由模板引擎进行解析。#parse指令导入的文件必须放在TEMPLATE_ROOT目录下,并且一次只能导入一个文件。允许在Velocity模板中嵌套执行#parse指令。最大深度由velocity.properties文件中的parse_directive.maxdepth定义。下面是一个例子:
Count down.
#set( $count = 8 )
#parse( "parsefoo.vm" )
All done with dofoo.vm!
包含的parsefoo.vm文件如下:
$count
#set( $count = $count - 1 )
#if( $count > 0 )
#parse( "parsefoo.vm" )
#else
All done with parsefoo.vm!
#end
输出结果是:
Count down.
8
7
6
5
4
3
2
1
0
All done with parsefoo.vm!
All done with dofoo.vm!
(6)#stop
#stop指令停止模板引擎的执行并返回。这在Debug时很有用。