Velocity学习笔记6——VTL中的引用

 
引用( Reference
VTL 中有3 种类型的引用:变量、属性和方法。作为一个使用VTL 的设计者,必须和同伴就引用的命名达成一致的意见,才能够在模板种正确的使用它。所有来自于引用的东西都会被作为字符串对待。如果一个引用指向一个对象而不是一个字符串,velocity 会调用该对象的toString() 方法来将该对象解决这个问题。(我的理解:由于velocity 引擎会将模板文件输出成另外的一个文本,因此velocity 引擎会试图将所有的引用都转换成string
 
变量( Variable
变量的速记符号由一个$ 开头,后面是一个VTL 的表示符。一个VTL 的标识符必须以一个字母开始(a-z A-Z) ,其他的部分必须是以下的字符:
字母(a-z A-Z),
数字(0-9)
连字符(-)
下划线(_)
下面就是一些有效的变量:
$foo
$mudSlinger
$mud-slinger
$mud_slinger
$mudSlinger1
 
VTL 引用是一个变量的时候,例如$foo ,这个变量的值可以从模板中的一个set 指示(directive )中获取,也可以从Java code 中获取。例如,如果在java 中将变量$foo 的值设置为了”bar” ,那么模板中的所有的$foo 都会用bar 来替代。另外一种方法是使用set 指示,例如:
#set( $foo = "pub" )
所有以后出现的$foo 都会被pub 替代。
 
 
属性
VTL 引用的第二种类型是属性(property) 。引用由特殊的格式。属性的速记符号是以$ 开始后面跟一个VTL 的标识符,再跟一个点(. )符号,再跟一个VTL 标识符。下面是VTL 中引用的例子:
 
$customer.Address
$purchase.Total
 
 
 
 
 
 
在第一个例子中,$customer.Address 可以有两种含义。第一种是:在customer 指向的hashtable 中寻找和key 值为Address 的值。第二种是:是一个方法调用;$customer.Address 可能是$customer.getAddress() 的缩写。Velocity 引擎会判断实际情况是这两种情况中的拿一种,并且返回恰当的值。
 
Methods
A method is defined in the Java code and is capable of doing something useful, like running a calculation or arriving at a decision. Methods are references that consist of a leading "$" character followed a VTL Identifier, followed by a VTL Method Body. A VTL Method Body consists of a VTL Identifier followed by an left parenthesis character ("("), followed by an optional parameter list, followed by right parenthesis character (")"). These are examples of valid method references in the VTL:
方法 (Method)
方法是Java 代码中定义的并且能够做某些事情,例如进行计算或做某些决定。VTL 中的方法引用是以$ 开始,跟着是一个VTL 标识符跟着是一个点符号(.) ,再跟着是一个VTL 的方法体。一个VTL 的方法体是一个VTL 标识符接着是一个左括号”(“ ,然后是操作参数列表,然后是右括号”)” 。下面是一些有效的VTL 方法引用的例子:
$customer.getAddress()
$purchase.getTotal()
$page.setTitle( "My Home Page" )
$person.setAttributes( ["Strange", "Weird", "Excited"] )
上面的例子中的前两个例子: $customer.getAddress() $purchase.getTotal() 与属性那一节中的例子很相似。实际上, $customer.Address 也可以看成是 $customer.getAddress() 的简写形式。这两种方式的不同之处是再方法中,可以指定参数的列表。下面的方法就可以用简写形式:
$sun.getPlanets()
$annelid.getDirt()
$album.getPhoto()
而下面的方法不能用简写形式
$sun.getPlanet( ["Earth", "Mars", "Neptune"] )
## 简写形式不能够传递参数
 
$sisyphus.pushRock()
## Velocity 会将 $sisyphus.Rock 认为是 $sisyphus.getRock()
 
$book.setTitle( "Homage to Catalonia" )
## 简写形式不能够传递参数
 

你可能感兴趣的:(velocity,sun)