asp.net模板引擎:二、NVelocity标签语详解

本文深入探讨了NVelocity模板引擎的变量、循环、条件语句、宏、停止执行、包含与解析、转义字符、内置对象和方法调用等功能,并通过实例展示了如何在模板文件中高效使用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




NVelocity标签语详解,以及NVelocity调用说明

1. 变量

  (1) 变量的定义:

 

1
2
3
4
5
6
7
#set($name = "hello") 说明:velocity中变量是弱类型的。
  当使用#set 指令时,括在双引号中的字面字符串将解析和重新解释,如下所示:
  #set($directoryRoot = "www" )
  #set($templateName = "index.vm" )
  #set($template = "$directoryRoot/$templateName" )
  $template
 输出将会是:www/index.vm


注:在velocity中使用$2.5这样的货币标识是没有问题得的,因为velocity中的变量总是以一个大写或者小写的字母开始的。


(2) 变量规范的写法


   

1
${name} ,也可以写成:$name。提倡用前面的写法。



(3) 变量的赋值:  

     

1
2
3
4
5
$name="hello"
赋值的左边必须是一个变量或者是属性引用。右边可以是下面六种类型之一:
变量引用,字面字符串,属性引用,方法引用,字面数字,数组列表。
#set( $monkeySay = ["Not", $my, "fault"] ) ## ArrayList
通过索引取值方法:$monkeySay.get_item(0)



2. 循环


   例子:

1
2
3
4
5
6
7
8
9
#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.


代码


//集合数据

1
2
3
4
5
6
7
8
9
10
11
12
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



1
2
3
4
5
6
7
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);



调用:

1
2
3
4
#foreach($Item in $dtdataist.Rows)
$Item.name</br>
$Item.age</br>
#end




//字典


1
2
3
4
5
6
7
8
//注: 进入foreach循环后的数据是KeyValuePair<T,T>对象.所以模板里是通过Key与Value属性取得键与值.
Dictionary<stringint> userDict = new Dictionary<stringint>();
userDict.Add("name", 20);
userDict.Add("李四", 24);
userDict.Add("王五", 30);
vc.Put("dtdataist",userDict);
调用:
$dtSubSortList.name


//数组


1
2
3
4
5
6
7
8
9
10
11
12
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


支持加载对象多级属性调用 如:


1
2
3
4
5
6
7
vc.Put("monkey"new { Say = new string[] { "Not""Yes""fault" } });
调用:$monkey.Say.get_item(0) 显示:Not
支持加载多个对象数组 如:
#set($tdata=[["Name:王风","age:100"],["Name:wangfeng","age:100"]])
$tdata.get_item(0).Name   显示:王风
#set($tdataa=[["Name王志康","age100"],["Namewangfeng","age100"]])
$tdataa.get_item(0).get_item(1)  显示:age100


提示:velocity中大小写敏感,不支持属性为汉字 如:$dtdataList.张三。

Velocity还特别提供了得到循环次数的方法,$velocityCount变量的名字是Velocity默认的名字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
这样可以通过$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. 条件语句

1
2
3
4
#if (condition)
#elseif (condition)
#else
#end


4. 语句的嵌套

1
2
3
4
5
6
7
8
9
10
#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 操作符。


1
2
3
4
5
6
7
8
9
10
11
12
## 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中的宏我们可以理解为函数。

①宏的定义

1
2
3
#macro(宏的名称 $参数1 $参数2 …)
 语句体(即函数体)
#end


②宏的调用


1
#宏的名称($参数1 $参数2 …)


说明:参数之间用空格隔开。


7.#stop


停止执行模板引擎并返回,把它应用于debug是很有帮助的。


8.#include与#parse


#include和#parse的作用都是引入本地文件, 为了安全的原因,被引入的本地文件只能在TEMPLATE_ROOT目录下。


区别:

(1) 与#include不同的是,#parse只能指定单个对象。而#include可以有多个

如果您需要引入多个文件,可以用逗号分隔就行:

1
#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

\\\$email

输出:

foo

$email

\foo

\$email

如果$email 未定义

$email

\$email

\\$email

\\\$email

输出:

$email

\$email

\\$email

\\$email

11.内置对象


Velocity内置了一些对象,在vm模版里可以直接调用,列举如下:

$request、$response、$session,目前还不清楚怎么调用。


12. 方法调用

代码

1
2
3
4
5
6
7
8
9
10
11
12
public class Tool
{
public string ConvertToString(string source)
{
return html + "_convert";
}
public static string C2()
{
return "test" "_c2";
}
}
vc.Put("toolobj", tool);



调用方法:

1
2
$toolobj.ConvertHtml("123456");
$toolobj.C2();


多参数方法调用public static string SomeMethod(params String[] args)

{

return String.Join('-', args);

}

调用方法:$instance.SomeMethod('arg1', 'arg2')


12.模板文件调用

1
2
3
4
5
6
7
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");//输出格式


//模板的缓存设置

1
2
3
4
5
6
7
8
9
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.youkuaiyun.com/space.php?uid=301568&do=blog&id=38145

3.http://www.castleproject.org/others/nvelocity/improvements.html

4.http://blog.youkuaiyun.com/zhanglei5415/archive/2010/08/04/5787131.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值