Velocity用户指南(三)

3)循环:foreach

 

下面是一个例子:

 

  •  

    #foreach( $product in $allProducts )

     

       

  • $product

     

    #end

     

 

$allProducts的内容可以是VectorHashtableArrayList,每次取出一个值赋值给$product;返回的值是一个Java对象,可以用来引用具体的方法。下面的例子假设$allProductsHashtable对象:

 

  •  

    #foreach( $key in $allProducts.keySet() )

     

       

  • Key: $key -> Value: $allProducts.get($key)

     

    #end

     

 

Velocity提供了访问循环计数变量的简单方法:

 

 

 

 

$velocityCount$customer.Name

 

$velocityCountVelocity表示循环计数的内部变量,缺省开始值为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],其中nm必须是整型:

 

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时很有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值