NVelocity系列:Getting Start With NVelocity (转)
NVelocity是java velocity的c#实现,目前我在CodePlex维护着与velocity同步的版本。NVelocity也在项目中使用着,在社区也有国外开发者的一些反馈。
下面是一个在Asp.Net如何使用NVelocity的非常简单例子:
定义HttpHandler:
1
namespace NVelocity.TestWebsite2
{3
using System;4
using System.Collections.Generic;5
using System.IO;6
using System.Web;7

8
using Commons.Collections;9

10
using NVelocity.App;11
using NVelocity.Context;12
using NVelocity.Runtime;13

14
/// <summary>15
/// 16
/// </summary>17
public class NVelocityHandler : IHttpHandler18
{19
#region IHttpHandler Members20

21
public bool IsReusable22
{23
get { return false; }24
}25

26
public void ProcessRequest(HttpContext context)27
{28
VelocityEngine velocity = new VelocityEngine();29

30
ExtendedProperties props = new ExtendedProperties();31

32
//定义模板路径33
props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Views"));34

35
//初始化36
velocity.Init(props);37

38
List<City> list = new List<City>();39

40
list.Add(new City() { Name = "sh", Id = 21 });41
list.Add(new City() { Name = "bj", Id = 22 });42
list.Add(new City() { Name = "tj", Id = 23 });43

44

45
IContext c = new VelocityContext();46

47
//添加到上下文中48
c.Put("cities", list);49

50
//根据请求输出51
velocity.MergeTemplate(context.Request.QueryString["vm"] + ".vm", "UTF-8", c, context.Response.Output);52
}53

54
#endregion55
}56

57
/// <summary>58
/// 城市59
/// </summary>60
public class City61
{62
/// <summary>63
/// ID64
/// </summary>65
public int Id { get; set; }66

67
/// <summary>68
/// 名称69
/// </summary>70
public string Name { get; set; }71
}72
}73

一个用于测试的default.vm模板文件:
1
##循环输出2
#foreach($city in $cities)3
Id:$city.id<br />4
城市名称:$city.name<br />5
#end6
##索引获取数据7
$cities.get_item(2).name8

在Web.config中配置上面定义的HttpHandler:
<httpHandlers>
<add verb="*" path="*.page" type="NVelocity.TestWebsite.NVelocityHandler,NVelocity.TestWebsite"/>
</httpHandlers>
请求及输出效果:




浙公网安备 33010602011771号