VelocityTemplateLanguage

来源:互联网 发布:excel数据透视表的作用 编辑:程序博客网 时间:2024/05/22 07:41

first:make a template:hollosite.vm:
   <html>
    <title>Hello Velocity</title>
    <body>
      Welcome $name to Javayou.com!
      today is $date.
    </body>
   </html>

second:Java code
   import java.io.StringWriter;
   import org.apache.velocity.app.VelocityEngine;
   import org.apache.velocity.Template;
   import org.apache.velocity.VelocityContext;
   public class HelloWorld{
    public void main(String[] args){
      //初始化 Velocity 模板引擎
      VelocityEngine ve = new VelocityEngine();
      ve.init();
      //Velocity 获取模板文件,得到模板引用
      Template t = ve.getTemplate("hollosite.vm");
      //初始化环境,并将数据放入环境
      VelocityContext vc = new VelocityContext();
      vc.put("name","jxd");
      vc.put("date",(new date()).toString());
      //将环境变量和输出部分结合
      StringWriter sw = new StringWriter();
      t.merge(vc,sw);
      System.out.println(sw.toString());
    }
   }
   
result:
 <html>
  <title>Hello Velocity</title>
  <body>
    Welcome jxd to Javayou.com!
    today is Tue Dec 14 19:26:37 CST 2004.
  </body>
 </html>

1:在Velocity中,变量的定义都是使用“$”开头的

2:用#set来设置变量,eg:#set ($admin="admin")

3:用#if,#else,#end,#foreach,来控制循环
eg: #foreach( $product in $list )
   <li>$product</li>
  #end

4:Velocity的内建变量$velocityCount,指的是默认的列举序号,从1开始

5:VTL支持单行注释(以##开始)和多行注释(包括在#*和*#之间)

6:<input type="text" name="email" value="$!email"/>
当$email没有值时,Velocity会用空串替代$email。

7:#macro相当于定义一个函数可以有参数:eg:
#macro (registerMessage $field)
    #if (!$field.valid) $field.message #end
#end
方法名为registerMessage,参数名为:$field
调用:#registerMessage ($!group.loginName)

8:#stop允许模板设计者停止执行模板引擎并返回

9:#parse允许模板设计者一个包含VTL的本地文件,eg:#parse( “me.vm” )

10:VTL中有三种类型reference:变量(variables),属性(properties),方法(methods)
  variables:$customer
  properties:$customer.Address
  methods:$customer.getAddress()
  这其中properties有两种含义,一:如果customer是一个Hashtable或是一个Map之类的,Address就相当于
  其中的键,$customer.Address得到他的值。二:customer表示一个对象,Address是他的方法,相当于
  $cuntomer.getAddress()
  上边$customer,$customer.Address,$customer.getAddress()都不是正式的写法,正式的写法应该是
      ${customer},${customer.Address},${customer.getAddress()},一般情况下这两种写法都是没错的。
    
11:在附值的时候,如果右边要附的值为null,则左边被附的值将指向一个已经存在的reference,eg:
  #set ( $resut = $query.criteria(“name”) )
   The result of the first query is $result
   #set ( $resut = $query.criteria(“address”) )
   The result of the second query is $result
  如果$query.criteria(“name”)返回一个“bill”,而$query.criteria(“address”)返回的是null,则显示的结果如下:
   The result of the first query is bill
   The result of the second query is bill
   为了解决以上问题我们要通过预先定义的方式给被附值的变量或属性或方法一个初值

12:#if ( $foo )
     <strong>Velocity!</strong>
   #end
  上例中的条件语句将在以下两种条件下成立:
  l  $foo是一个boolean型的变量,且它的值为true
  2  $foo变量的值不为null