VelocityHelper模板工具类

1 /******************************************************************
2 * 类名称:VelocityHelper模板工具类
3 * 类说明:用于配置VelocityEngine对象的相关属性和封装常用的操作代码
4 * 作者:何海阔
5 * 编写日期:2011-02-11
6 * 修改人:
7 * 修改日期:
8 * 更新记录:
9 *******************************************************************/
10 using System;
11 using System.Web;
12 using System.IO;
13 using NVelocity;
14 using NVelocity.App;
15 using NVelocity.Context;
16 using NVelocity.Runtime;
17 using Commons.Collections;
18 using System.Text;
19
20 namespace VelocityHelper
21 {
22 /// <summary>
23 /// NVelocity模板工具类 VelocityHelper
24 /// </summary>
25 public class Velocity
26 {
27 private VelocityEngine velocity = null;
28 private IContext context = null;
29
30 /// <summary>
31 /// 构造函数
32 /// </summary>
33 /// <param name="templatDir">模板文件夹路径</param>
34 public Velocity(string templatDir)
35 {
36 Init(templatDir);
37 }
38
39 /// <summary>
40 /// 无参数构造函数
41 /// </summary>
42 public Velocity() { }
43
44 /// <summary>
45 /// 初始话NVelocity模块
46 /// </summary>
47 public void Init(string templatDir)
48 {
49 //创建VelocityEngine实例对象
50 velocity = new VelocityEngine();
51
52 //使用设置初始化VelocityEngine
53 //ExtendedProperties props = new ExtendedProperties();
54 //props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
55 velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.IO.Path.GetFullPath(".\\") + templatDir);
56 //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath));
57 //props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
58 //props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
59
60 //模板的缓存设置
61 //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true); //是否缓存
62 //props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)30); //缓存时间(秒)
63
64 velocity.Init();
65
66 //为模板变量赋值
67 context = new VelocityContext();
68 }
69
70 /// <summary>
71 /// 给模板变量赋值
72 /// </summary>
73 /// <param name="key">模板变量</param>
74 /// <param name="value">模板变量值</param>
75 public void Put(string key, object value)
76 {
77 if (context == null)
78 context = new VelocityContext();
79 context.Put(key, value);
80 }
81
82 /// <summary>
83 /// 显示模板
84 /// </summary>
85 /// <param name="templatFileName">模板文件名</param>
86 public string Display(string templatFileName)
87 {
88 //从文件中读取模板
89 Template template = velocity.GetTemplate(templatFileName);
90 //合并模板
91 StringWriter writer = new StringWriter();
92 template.Merge(context, writer);
93 //输出
94 return writer.ToString();
95 }
96 }
97 }

posted on 2011-02-22 11:16  HaiKuo  阅读(932)  评论(0)    收藏  举报

导航