使用NVelocity也有幾個(gè)年頭了,主要是在我的代碼生成工具Database2Sharp上使用來(lái)生成相關(guān)代碼的,不過(guò)NVelocity是一個(gè)非常不錯(cuò)的模板引擎,可以用來(lái)生成文件、頁(yè)面等相關(guān)處理,非常高效和方便。
它原先是在網(wǎng)站http://nvelocity.sourceforge.net/上維護(hù),不過(guò)從0.41后,該網(wǎng)站就不再進(jìn)行NVelocity更新了,現(xiàn)在可以在網(wǎng)站http://nvelocity.codeplex.com/上獲得最新版本的更新,接著版本的更新操作,我們把NVelocity的幾種生成文件的操作介紹一下,以便大家進(jìn)行更深入的了解。
我在早期幾篇文章也介紹過(guò)NVelocity的使用,主要介紹了NVelocity的語(yǔ)法和邏輯的和使用,還有就是如何在實(shí)際項(xiàng)目中進(jìn)行的內(nèi)容動(dòng)態(tài)生成的操作,有興趣可以翻下下面幾篇文章:
強(qiáng)大的模板引擎開源軟件NVelocity
Database2Sharp版本更新之自定義模板生成
使用NVelocity0.5實(shí)現(xiàn)服務(wù)器端頁(yè)面自動(dòng)生成

從上面的圖示,我們可以看到,NVelocity的模板化生成包含了3種方式,一種是從文件到文件或者字符串,一種是從字符串到字符串,他們各自的處理方式有所不同,但是都能正確解析里面的內(nèi)容。
為了更好利用NVelocity的特性,我們對(duì)它進(jìn)行一個(gè)初步的輔助類封裝。
/// <summary> /// 基于NVelocity的模板文件生成輔助類 /// </summary> public class NVelocityHelper { PRotected VelocityContext context; protected Template template; protected string templateFile; /// <summary> /// 存放鍵值的字典內(nèi)容 /// </summary> private Dictionary<string, object> KeyObjDict = new Dictionary<string, object>(); /// <summary> /// 添加一個(gè)鍵值對(duì)象 /// </summary> /// <param name="key">鍵,不可重復(fù)</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方法,主要用來(lái)為模板引擎添加一些需要綁定在頁(yè)面上的變量對(duì)象,這樣頁(yè)面變量參數(shù)的內(nèi)容就能正確解析出來(lái)了。
為了使用NVelocity的各種特性,我們需要在輔助類里面構(gòu)造模板的相關(guān)信息,設(shè)置相關(guān)參數(shù)。
/// <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"); //如果設(shè)置了FILE_RESOURCE_LOADER_PATH屬性,那么模板文件的基礎(chǔ)路徑就是基于這個(gè)設(shè)置的目錄,否則默認(rèn)當(dāng)前運(yùn)行目錄 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); } }在生成內(nèi)容之前,需要把相關(guān)的對(duì)象屬性綁定到模板引擎的上下文對(duì)象里面。
/// <summary> /// 初始化上下文的內(nèi)容 /// </summary> private void InitContext() { context = new VelocityContext(); foreach (string key in KeyObjDict.Keys) { context.Put(key, KeyObjDict[key]); } }1)根據(jù)模板文件構(gòu)造對(duì)應(yīng)的文件內(nèi)容
/// <summary> ///根據(jù)模板創(chuàng)建輸出的文件,并返回生成的文件路徑 /// </summary> public virtual string ExecuteFile() { string fileName = ""; if (template != null) { string filePath = CheckEndBySlash(directoryOfOutput); fileName = filePath + fileNameOfOutput + fileExtension; if (!string.IsNullOrEmpty(filePath) && !Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } //LogTextHelper.Debug(string.Format("Class file output path:{0}", fileName)); InitContext(); using (StreamWriter writer = new StreamWriter(fileName, false)) { template.Merge(context, writer); } } return fileName; }2)根據(jù)模板文件構(gòu)造字符串內(nèi)容
/// <summary> /// 根據(jù)模板輸出字符串內(nèi)容 /// </summary> /// <param name="templateFile"></param> /// <returns></returns> public string ExecuteString() { InitContext(); System.IO.StringWriter writer = new System.IO.StringWriter(); template.Merge(context, writer); return writer.GetStringBuilder().ToString(); }3)根據(jù)字符串內(nèi)容構(gòu)造字符串輸出
/// <summary> /// 合并字符串的內(nèi)容 /// </summary> /// <returns></returns> public string ExecuteMergeString(string inputString) { VelocityEngine templateEngine = new VelocityEngine(); templateEngine.Init(); InitContext(); System.IO.StringWriter writer = new System.IO.StringWriter(); templateEngine.Evaluate(context, writer, "mystring", inputString); return writer.GetStringBuilder().ToString(); }上面幾種操作模板輸出的方式,其調(diào)用代碼如下所示。
private void btnGenerateFile_Click(object sender, EventArgs e) { string tempalte = "Template/template.htm";//相對(duì)目錄 TestInfo info = new TestInfo(); info.Title = "測(cè)試標(biāo)題"; info.Content = "測(cè)試內(nèi)容,這是測(cè)試內(nèi)容"; info.Datetime = DateTime.Now; NVelocityHelper adapter = new NVelocityHelper(tempalte); adapter.AddKeyValue("title", "This is a title") .AddKeyValue("content", "This is a Content") .AddKeyValue("datetime", System.DateTime.Now) .AddKeyValue("TestInfo", info); adapter.FileNameOfOutput = "testTemplate"; string filePath = adapter.ExecuteFile(); if (!string.IsNullOrEmpty(filePath)) { Process.Start(filePath); } } private void btnGenerate_Click(object sender, EventArgs e) { string tempalte = "Template/template.htm";//相對(duì)目錄 TestInfo info = new TestInfo(); info.Title = "測(cè)試標(biāo)題"; info.Content = "測(cè)試內(nèi)容,這是測(cè)試內(nèi)容"; info.Datetime = DateTime.Now; NVelocityHelper adapter = new NVelocityHelper(tempalte); adapter.AddKeyValue("title", "This is a title") .AddKeyValue("content", "This is a Content") .AddKeyValue("datetime", System.DateTime.Now) .AddKeyValue("TestInfo", info); this.txtCode.Text = adapter.ExecuteString(); } private void btnMergeString_Click(object sender, EventArgs e) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.Append( "${Title}/r/n" + "$Content/r/n" + "$Digest/r/n" + "$Author/r/n" + "$KeyWord/r/n" + "$DateTime/r/n"); NVelocityHelper adapter = new NVelocityHelper(); adapter.AddKeyValue("Title", "標(biāo)題"). AddKeyValue("Content", "內(nèi)容"). AddKeyValue("Digest", "摘要"). AddKeyValue("Author", "作者"). AddKeyValue("Keyword", "關(guān)鍵詞"). AddKeyValue("DateTime", DateTime.Now); this.txtCode.Text = adapter.ExecuteMergeString(builder.ToString()); }上面的幾種操作模板內(nèi)容的方式,能夠在絕大多數(shù)情況下滿足我們的應(yīng)用要求,如可以在代碼生成工具里面,定義一些自定義的內(nèi)容模板,然后結(jié)合數(shù)據(jù)庫(kù)的元數(shù)據(jù)信息,實(shí)現(xiàn)豐富邏輯的代碼生成操作。

也可以在一些內(nèi)容管理的應(yīng)用上(如文章管理方面),根據(jù)輸入的內(nèi)容,實(shí)現(xiàn)文章內(nèi)容的文件生成操作,這個(gè)生成后,我們就直接使用文章的文件鏈接地址就可以了。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注