NVelocity用法 Net版(完全整理)

时间:2022-11-24 18:57:11

摘要: 本文采用NVelocity 1.1.1最新版 下载地址http://sourceforge.net/projects/castleproject/files/NVelocity/1.1 /CastleNVelocity-1.1.1.zip/download。所有标签功能都经过测试通过。一、NVelocity介绍 1.1 Velocity是 ...2. 循环
   例子:
 #set( $list = ["pine", "oak", "maple"])
    #foreach ($element in $list)
     $element index is $velocityCount
     This is $element.<br>
     #end
    输出的结果为:
    1 pine is 1.
    2 oak is 2. 
    3 maple is 3.
代码 
 //集合数据
List<object> users = new List<object>()
 {
      new {Name = "张三", age=20},
      new {Name = "李四", age=24},
      new {Name = "王五", age=30}
};
      vc.Put("dtdataist",users);
     调用:
     #foreach($Item in $dtdataist)
       $Item.name</br>
       $Item.age</br>
       #end
 System.Data.DataTable userTable = new System.Data.DataTable();
     userTable.Columns.Add("Name", typeof(string));
     userTable.Columns.Add("Age", typeof(int));
     userTable.Rows.Add("张三", 20);
     userTable.Rows.Add("李四", 24);
     userTable.Rows.Add("王五", 30);
     vc.Put("dtdataist",userTable);
      调用:
      #foreach($Item in $dtdataist.Rows)
        $Item.name</br>
        $Item.age</br>
        #end
       //字典
     //注: 进入foreach循环后的数据是KeyValuePair<T,T>对象.所以模板里是通过Key与Value属性取得键与值.
            Dictionary<string, int> userDict = new Dictionary<string, int>();
            userDict.Add("name", 20);
            userDict.Add("李四", 24);
            userDict.Add("王五", 30);
           vc.Put("dtdataist",userDict);
          调用:
           $dtSubSortList.name
            //数组
            object[] userArray = new object[]{
                new {Name = "张三", age=20},
                new {Name = "李四", age=24},
                new {Name = "王五", age=30}
            };
            vc.Put("dtdataist", userArray);
          调用:
         #foreach($Item in $dtdataist)
           $Item.name</br>
           $Item.age</br>
           #end
支持加载对象多级属性调用 如:
vc.Put("monkey", new { Say = new string[] { "Not", "Yes", "fault" } });
调用:$monkey.Say.get_item(0)
 提示:velocity中大小写敏感,不支持属性为汉字 如:$dtdataList.张三。
Velocity还特别提供了得到循环次数的方法,$velocityCount变量的名字是Velocity默认的名字。
这样可以通过$velocityCount%2==0 判断奇数偶数行。
each($data in $datas)
#before 
    this before</br> #before--数据的开始处
#odd
   $data is odd</br>#odd--数据的奇数处
#even
    $data is even</br>#even--数据的偶数处
#each
   $data is even</br>#each--可以循环美行数据
#between
   this is between</br>每行数据的间隔处,如:1-2之间,2-3之间。
#after
  after</br>--#after数据的结束处
#end
3. 条件语句
#if (condition) 
#elseif (condition) 
#else 
#end
4. 语句的嵌套
#foreach ($element in $list) 
 ## inner foreach 内循环 
 #foreach ($element in $list) 
 This is $element. $velocityCount <br>inner<br>
 #end 
 ## inner foreach 内循环结束 
## outer foreach 
This is $element. 
$velocityCount <br>outer<br>
#end
语句中也可以嵌套其他的语句,如#if…#else…#end等。
5. 关系和逻辑操作符
Velocity 也具有逻辑AND, OR 和 NOT 操作符。 

## example for AND
#if($foo && $bar)
 <strong> This AND that</strong>
#end
## example for OR
#if($foo || $bar)
 <strong> This OR that</strong>
#end
## example for NOT
#if(!$foo)
 <strong> This NOTthat</strong>
#end
 例 子中#if() 指令仅在$foo 和$bar 斗为真的时候才为真。如果$foo 为假,则表达式也为假;并且 $bar 将不被求值。如果 $foo 为真,Velocity 模板引擎将继续检查$bar的值,如果 $bar 为真,则整个表达式为真。并且输出This AND that 。如果 $bar 为假,将没有输出因为整个表达式为假。
6.Velocity 中的宏
Velocity中的宏我们可以理解为函数。
①宏的定义
#macro(宏的名称 $参数1 $参数2 …)
 语句体(即函数体)
#end
②宏的调用
#宏的名称($参数1 $参数2 …)
说明:参数之间用空格隔开。
7.#stop
 停止执行模板引擎并返回,把它应用于debug是很有帮助的。
8.#include与#parse
#include和#parse的作用都是引入本地文件, 为了安全的原因,被引入的本地文件只能在TEMPLATE_ROOT目录下。
区别:
(1) 与#include不同的是,#parse只能指定单个对象。而#include可以有多个
如果您需要引入多个文件,可以用逗号分隔就行:
#include ("template/one.gif" "template/two.txt" "template/three.htm" )
在括号内可以是文件名,但是更多的时候是使用变量的:
#set($seasonalstock ="template/test.htm")
#include ("template/greetings.txt" $seasonalstock)(注意中间没有分隔符)
(2) #include被引入文件的内容将不会通过模板引擎解析; 
而#parse引入的文件内容Velocity将解析其中的velocity语法并移交给模板,意思就是说相当与把引入的文件copy到文件中。
#parse是可以递归调用的,例如:如果dofoo.vm包含如下行:
Count down.<br>
#set ($count = 8)
#parse ("parsefoo.vm")
<br>All done with dofoo.vm!
那么在parsefoo.vm模板中,你可以包含如下VTL:
$count
#set($count = $count - 1)
#if ( $count > 0 )<br>
#parse( "parsefoo.vm" )
#else
<br>All done with parsefoo.vm!
#end的显示结果为:
Count down.
8
7
6
5
4
3
2
1
0
All done with parsefoo.vm!
All done with dofoo.vm!
注意:在vm中使用#parse来嵌套另外一个vm时的变量共享问题。如:
->a.vm 里嵌套 b.vm;
->a.vm 里定义了变量 $param;
->b.vm 里可以直接使用$param,无任何限制。
但需要特别注意的是,如果b.vm里同时定义有变量$param,则b.vm里将使用b.vm里定义的值。
9.转义字符'\'的使用
如果reference被定义,两个’\’意味着输出一个’\’,如果未被定义,刚按原样输出。如:
#set($email = "foo" )
$email
\$email
\\$email <file:///\\$email\>
\\\$email
输出:
foo
$email
\foo
\$email
如果$email 未定义
$email
\$email
\\$email <file:///\\$email\>
\\\$email
输出:
$email
\$email
\\$email <file:///\\$email\>
\\$email <file:///\\$email>
11.内置对象
Velocity内置了一些对象,在vm模版里可以直接调用,列举如下:
$request、$response、$session,目前还不清楚怎么调用。
12. 方法调用
代码 
public class Tool
{
    public string ConvertToString(string source)
    {
        return html + "_convert";
    }
    public static string C2()
    {
        return "test" + "_c2";
    }
}
 vc.Put("toolobj", tool);
调用方法:
$toolobj.ConvertHtml("123456");
$toolobj.C2();
多参数方法调用public static string SomeMethod(params String[] args)
{
  return String.Join('-', args);
}
调用方法:$instance.SomeMethod('arg1', 'arg2')
 12.模板文件调用
代码 
VelocityEngine ve = new VelocityEngine();//模板引擎实例化
ExtendedProperties ep = new ExtendedProperties();//模板引擎参数实例化
ep.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");//指定资源的加载类型
ep.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath("."));//指定资源的加载路径
//props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath));
 ep.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");//输入格式
ep.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");//输出格式
//模板的缓存设置
ep.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true);              //是否缓存
ep.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)300);    //缓存时间(秒)
ve.Init(ep);
Template t = ve.GetTemplate("template/a.htm");//加载模板
VelocityContext vc = new VelocityContext(); //当前的数据信息载体集合
vc.Put("list", new {users = GetList(), age = 20 });//输入list标签的数据,模板标签为$list
  ........
t.Merge(vc, context.Response.Output);//合并数据集合对象到输出流.
参考地址:
1.http://www.cnblogs.com/wysky/archive/2007/12/06/985832.html
2.http://student.csdn.net/space.php?uid=301568&do=blog&id=38145
3.http://www.castleproject.org/others/nvelocity/improvements.html
4.http://blog.csdn.net/zhanglei5415/archive/2010/08/04/5787131.aspx