`
lujar
  • 浏览: 494884 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

阅读更多
 
引用(Reference
VTL中有3种类型的引用:变量、属性和方法。作为一个使用VTL的设计者,必须和同伴就引用的命名达成一致的意见,才能够在模板种正确的使用它。所有来自于引用的东西都会被作为字符串对待。如果一个引用指向一个对象而不是一个字符串,velocity会调用该对象的toString()方法来将该对象解决这个问题。(我的理解:由于velocity引擎会将模板文件输出成另外的一个文本,因此velocity引擎会试图将所有的引用都转换成string
 
变量(Variable
变量的速记符号由一个$开头,后面是一个VTL的表示符。一个VTL的标识符必须以一个字母开始(a-zA-Z),其他的部分必须是以下的字符:
字母(a-zA-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" )
## 简写形式不能够传递参数
 

相关推荐

Global site tag (gtag.js) - Google Analytics