.Net下模板引擎NVelocity的封装类――VelocityHelper

NVelocity是Java模板引擎Velocity的.Net版本。NVelocity目前官方版本为0.42。官方地址:http://nvelocity.sourceforge.net/,原作者已经申明不再对NVelocity做技术支持了,所以sourceforge上NVelocity版本一直是0.42不再有更新了。不过目前NVelocity已经有1.0的版本了,是由castleproject项目维护的。NVelocity.dll能在castle项目中找到。Castleproject地址:http://www.castleproject.org/。使用NVelocity模板技术需要学习VTL

要使用NVelocity模板技术需要学习VTL语言。网络上关于NVelocity的VTL语言介绍的比较少,不过没有关系,由于NVelocity是有Velocity移植过来的所以Velocity的VTL语言完全适用于NVelocity。下面我们来封装一个VelocityHelper类以方便NVelocity在在.NET中使用

VelocityHelper.cs 文件

using System;
using System;
using System.Web;
using System.IO;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using Commons.Collections;
 
/// 
/// NVelocity模板工具类 VelocityHelper
/// 
public class VelocityHelper
{
private VelocityEngine velocity = null;
private IContext context = null;
/// 
/// 构造函数
/// 
///
模板文件夹路径
public VelocityHelper(string templatDir)
{
Init(templatDir);
}
/// 
/// 无参数构造函数
/// 
public VelocityHelper() { ;}
/// 
/// 初始话NVelocity模块
/// 
///
模板文件夹路径
public void Init(string templatDir)
{
//创建VelocityEngine实例对象
velocity = new VelocityEngine();
 
//使用设置初始化VelocityEngine
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir));
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
velocity.Init(props);
 
//为模板变量赋值
context = new VelocityContext();
}
/// 
/// 给模板变量赋值
/// 
///
模板变量
///
模板变量值
public void Put(string key, object value)
{
if (context == null)
context = new VelocityContext();
context.Put(key, value);
}
/// 
/// 显示模板
/// 
///
模板文件名
public void Display(string templatFileName)
{
//从文件中读取模板
Template template = velocity.GetTemplate(templatFileName);
//合并模板
StringWriter writer = new StringWriter();
template.Merge(context, writer);
//输出
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}

使用方法:

VelocityHelper vh = new VelocityHelper();
vh.Init(@"templates");//指定模板文件的相对路径
vh.Put("title", "员工信息");
vh.Put("comName","成都xxxx里公司");
vh.Put("property","天营");
vh.Put("comAddress","四川成都市");
 
ArrayList aems = new ArrayList();
aems.Add(new EM("小李",22,"男"));
aems.Add(new EM("小王",21,"女"));
aems.Add(new EM("小周",22,"男"));
aems.Add(new EM("小瓜",32,"男"));
vh.Put("aems", aems);
 
//使用tp1.htm模板显示
vh.Display("tp1.htm");

注意上面只有关键性的代码,如EM为员工类。完整代码请在下面下载。

找不到NVelocity.dll的朋友可以在这里下载:

VelocityHelper封装类以及使用Demo 其中的NVelocity.dll是1.0版本的

Velocity中文手册下载这个VLT语言一样适用于NVelocity

原文地址:https://www.cnblogs.com/yasin/p/1703212.html