Velocity的中文指南(3)-整理

类别:Java 点击:0 评论:0 推荐:
1.       循环 1.1.     Foreach 循环

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

<ul>

#foreach( $product in $allProducts )

    <li>$product</li>

#end

</ul>

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

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

 

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

 

<ul>

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

    <li>Key: $key -> Value: $allProducts.get($key)</li>

#end

</ul>

 

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

<table>

#foreach( $customer in $customerList )

    <tr><td>$velocityCount</td><td>$customer.Name</td></tr>

#end

</table>

 

循环计数变量的缺省名称是$velocityCount,在velocity.properties 配置文件中标明。默认情况下,该变量从1开始计数,但是可以在velocity.properties 文件中设为从0或者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

 

2.       包含

#include 脚本元素允许模板设计人员包含(导入)本地文件, 这个文件将插入到#include 指令被定义的地方。文件的内容并不通过模板引擎来渲染。处于安全的原因,被包含的文件只可以放在TEMPLATE_ROOT下。

 

#include( "one.txt" )

 #include 指令引用的文件在双引号内。如果超过一个文件,其间用逗号隔开。

#include( "one.gif","two.txt","three.htm" )

 

被包含的文件并不是一定要用文件名来引用,事实上,最好的办法是使用变量而不是文件名。这在根据规则决定何时提交页面时,决定目标输出是很有用的。

#include( "greetings.txt", $seasonalstock )

 

 

3.       解析

 #parse 脚本元素允许页面设计员导入包含VTL的本地文件。 Velocity将解析和渲染指定的模板。

#parse( "me.vm" )

 

就象 #include 指令,#parse 可以使用变量而不是一个实在的模板文件。#parse 引用的模板文件必须包含的TEMPLATE_ROOT指定的目录之下。和 #include 指令不一样, #parse 只有一个参数。

VTL 模板templates can have #parse statements referring to templates that in turn have #parse statements. By default set to 10, the parse_directive.maxdepth line of the velocity.properties allows users to customize maximum number of #parse referrals that can occur from a single template. (Note: If the parse_directive.maxdepth property is absent from the velocity.properties file, Velocity will set this default to 10.) Recursion is permitted, for example, if the template dofoo.vm contains the following lines:

Count down.

#set( $count = 8 )

#parse( "parsefoo.vm" )

All done with dofoo.vm!

 

It would reference the template parsefoo.vm, which might contain the following VTL:

$count

#set( $count = $count - 1 )

#if( $count > 0 )

    #parse( "parsefoo.vm" )

#else

    All done with parsefoo.vm!

#end

 

After "Count down." is displayed, Velocity passes through parsefoo.vm, counting down from 8. When the count reaches 0, it will display the "All done with parsefoo.vm!" message. At this point, Velocity will return to dofoo.vm and output the "All done with dofoo.vm!" message.

 

4.       停止

 

 #stop 脚本允许模板设计员停止模板引擎的执行,并返回。这通常用作调试。

#stop

本文地址:http://com.8s8s.com/it/it14715.htm