基于NVelocity的几种内容生成方式汇总

2019-05-22 10:10:56王振洲

使用NVelocity也有几个年头了,主要是在我的代码生成工具Database2Sharp上使用来生成相关代码的,不过NVelocity是一个非常不错的模板引擎,可以用来生成文件、页面等相关处理,非常高效和方便。

它原先是在网站http://nvelocity.sourceforge.net/ 上维护,不过从0.41后,该网站就不再进行NVelocity更新了,现在可以在网站http://nvelocity.codeplex.com/上获得最新版本的更新,接着版本的更新操作,我们把NVelocity的几种生成文件的操作介绍一下,以便大家进行更深入的了解。

1、基于NVelocity的几种内容生成方式

从上面的图示,我们可以看到,NVelocity的模板化生成包含了3种方式,一种是从文件到文件或者字符串,一种是从字符串到字符串,他们各自的处理方式有所不同,但是都能正确解析里面的内容。

为了更好利用NVelocity的特性,我们对它进行一个初步的辅助类封装。

/// <summary>
/// 基于NVelocity的模板文件生成辅助类
/// </summary>
public class NVelocityHelper
{
protected VelocityContext context;
protected Template template;
protected string templateFile;
/// <summary>
/// 存放键值的字典内容
/// </summary>
private Dictionary<string, object> KeyObjDict = new Dictionary<string, object>();
/// <summary>
/// 添加一个键值对象
/// </summary>
/// <param name="key">键,不可重复</param>
/// <param name="value">值</param>
/// <returns></returns>
public NVelocityHelper AddKeyValue(string key, object value)
{
if (!KeyObjDict.ContainsKey(key))
{
KeyObjDict.Add(key, value);
}
return this;
}................

上面的AddKeyValue方法,主要用来为模板引擎添加一些需要绑定在页面上的变量对象,这样页面变量参数的内容就能正确解析出来了。

为了使用NVelocity的各种特性,我们需要在辅助类里面构造模板的相关信息,设置相关参数。

/// <summary>
/// 初始化模板引擎
/// </summary>
protected virtual void InitTemplateEngine()
{
try
{
//Velocity.Init(NVELOCITY_PROPERTY);
VelocityEngine templateEngine = new VelocityEngine();
templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
//如果设置了FILE_RESOURCE_LOADER_PATH属性,那么模板文件的基础路径就是基于这个设置的目录,否则默认当前运行目录
templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);
templateEngine.Init();
template = templateEngine.GetTemplate(templateFile);
}
catch (ResourceNotFoundException re)
{
string error = string.Format("Cannot find template " + templateFile);
LogTextHelper.Error(error);
throw new Exception(error, re);
}
catch (ParseErrorException pee)
{
string error = string.Format("Syntax error in template " + templateFile + ":" + pee.StackTrace);
LogTextHelper.Error(error);
throw new Exception(error, pee);
}
}