使用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);}}
新聞熱點
疑難解答
圖片精選