Velocity用户手册---中文版(方法摘抄)



在VTL中有三种类型的references:变量(variables)、属性(properties)、方法(methods)。

声明:


声明一个Velocity引用变量 Everything coming to and from a reference被作为一个String对象处理。如果有一个对象$foo是一个Integer对象,那么Velocity将调用它的toString()方法将这个对象转型为String类型。 

 #set ( $a = “Velocity” );

方法和属性:

 $customer.Address 
 customer的类型可以是一个自定义java对象也可以是一个键值对Map。 Address可以是一个叫Address变量,也可以使getAddress()方法。

方法的入参

  $page.setTitle( “My Home Page” )  -----入参是字符串
  $person.setAttributes( [“Strange”, “Weird”, “Excited”] ) -----入参是列表集合

  $monkey.Say.get(0)  取值

空值替换符!quiet reference notation

$!email email是null时候显示"" 。很友好

简单算术

#set ( $value = $foo + 1 ) 
#set ( $value = $bar -1 ) 
#set ( $value = $foo * $bar ) 
#set ( $value = $foo / $bar ) 

逻辑判断

这里需要注意一点:Velocity context仅仅能够包含对象,所以当我们说“boolean”时实际上代表的时一个Boolean对象。即便某个方法返回的是一个boolean值,Velocity也会利用内省机制将它转换为一个Boolean的相同值。 
如果条件成立,那么#if和#end之间的内容将被显示。                                                 

  #if( $foo < 10 ) 
    <strong> Go North </strong> 
  #elseif( $foo == 10 ) 
    <strong> Go East </strong> 
  #elseif( $foo == 6 ) 
    <strong> Go South </strong> 
  #else 
    <strong> Go West </strong> 
  #end 

使用==判断比较两边是否相等

当你使用#set directive,String literal封闭在一对双引号内。 

循环 

  Foreach循环 
  例子: 
    <ul> 
      #foreach ( $product in $allProducts ) 
        <li> $product </li> 
      #end 
    </ul> 

$allProducts可以是一个Vector、Hashtable或者Array。分配给$product的值是一个java对象,并且可以通过变量被引用。例如:如果$product是一个java的Product类,并且这个产品的名字可以通过调用他的getName()方法得到。

现在我们假设$allProducts是一个Hashtable,如果你希望得到它的key应该像下面这样: 
<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默认的名字,你也可以通过修改velocity.properties文件来改变它。默认情况下,计数从“1”开始,但是你可以在velocity.properties设置它是从“1”还是从“0”开始。



你可能感兴趣的:(Velocity用户手册---中文版(方法摘抄))