基于NVelocity的幾種內(nèi)容生成方式匯總
使用NVelocity也有幾個年頭了,主要是在我的代碼生成工具Database2Sharp上使用來生成相關(guān)代碼的,不過NVelocity是一個非常不錯的模板引擎,可以用來生成文件、頁面等相關(guān)處理,非常高效和方便。
它原先是在網(wǎng)站http://nvelocity.sourceforge.net/ 上維護,不過從0.41后,該網(wǎng)站就不再進行NVelocity更新了,現(xiàn)在可以在網(wǎng)站http://nvelocity.codeplex.com/上獲得最新版本的更新,接著版本的更新操作,我們把NVelocity的幾種生成文件的操作介紹一下,以便大家進行更深入的了解。
1、基于NVelocity的幾種內(nèi)容生成方式

從上面的圖示,我們可以看到,NVelocity的模板化生成包含了3種方式,一種是從文件到文件或者字符串,一種是從字符串到字符串,他們各自的處理方式有所不同,但是都能正確解析里面的內(nèi)容。
為了更好利用NVelocity的特性,我們對它進行一個初步的輔助類封裝。
/// <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>
/// 添加一個鍵值對象
/// </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方法,主要用來為模板引擎添加一些需要綁定在頁面上的變量對象,這樣頁面變量參數(shù)的內(nè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ǔ)路徑就是基于這個設(shè)置的目錄,否則默認當前運行目錄
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)的對象屬性綁定到模板引擎的上下文對象里面。
/// <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)造對應(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";//相對目錄
TestInfo info = new TestInfo();
info.Title = "測試標題";
info.Content = "測試內(nèi)容,這是測試內(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";//相對目錄
TestInfo info = new TestInfo();
info.Title = "測試標題";
info.Content = "測試內(nèi)容,這是測試內(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", "標題").
AddKeyValue("Content", "內(nèi)容").
AddKeyValue("Digest", "摘要").
AddKeyValue("Author", "作者").
AddKeyValue("Keyword", "關(guān)鍵詞").
AddKeyValue("DateTime", DateTime.Now);
this.txtCode.Text = adapter.ExecuteMergeString(builder.ToString());
}
2、模板引擎NVelocity的幾種應(yīng)用場景
上面的幾種操作模板內(nèi)容的方式,能夠在絕大多數(shù)情況下滿足我們的應(yīng)用要求,如可以在代碼生成工具里面,定義一些自定義的內(nèi)容模板,然后結(jié)合數(shù)據(jù)庫的元數(shù)據(jù)信息,實現(xiàn)豐富邏輯的代碼生成操作。

也可以在一些內(nèi)容管理的應(yīng)用上(如文章管理方面),根據(jù)輸入的內(nèi)容,實現(xiàn)文章內(nèi)容的文件生成操作,這個生成后,我們就直接使用文章的文件鏈接地址就可以了。

或者根據(jù)數(shù)據(jù)信息生成具體的頁面,用于套打操作,如下是Winform里面的套打處理。


以上所述是小編給大家介紹的基于基于NVelocity的幾種內(nèi)容生成方式匯總,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
asp.net中利用ajax獲取動態(tài)創(chuàng)建表中文本框的值
通常在做主從表的數(shù)據(jù)錄入中,會碰到在一個頁面上同時錄入主表數(shù)據(jù)和從表數(shù)據(jù),主表的數(shù)據(jù)只有一條,從表的數(shù)據(jù)有一條到多條,這樣就要動態(tài)創(chuàng)建從表數(shù)據(jù)錄入入口。2010-03-03
.Net Core自動化部署之利用docker版jenkins部署dotnetcore應(yīng)用的方法
這篇文章主要給大家介紹了關(guān)于.Net Core自動化部署之利用docker版jenkins部署dotnetcore應(yīng)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06
asp.net textbox javascript實現(xiàn)enter與ctrl+enter互換 文本框發(fā)送消息與換行(類似
今天與大家分享一下 asp.net textbox javascript實現(xiàn)enter與ctrl+enter互換 文本框發(fā)送消息與換行(類似于QQ),這個功能到底怎么實現(xiàn)?首先聲明以下幾點2012-01-01
ASP.NET?MVC打印表格并實現(xiàn)部分視圖表格打印
這篇文章介紹了ASP.NET?MVC打印表格并實現(xiàn)部分視圖表格打印的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
Visual Studio中調(diào)試 .NET源代碼的實現(xiàn)步驟
在調(diào)試 .NET 應(yīng)用程序時,有時你可能需要查看其他人的源代碼,本文主要介紹了Visual Studio中調(diào)試 .NET源代碼的實現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2024-03-03
asp.net Silverlight應(yīng)用程序中獲取載體aspx頁面參數(shù)
有時候SL應(yīng)用中需要使用由aspx頁面中傳遞過來的參數(shù)值,此時通常有兩種方法獲取2009-11-11
在應(yīng)用程序級別之外使用注冊為allowDefinition=''MachineToApplication''的節(jié)是錯誤的
在應(yīng)用程序級別之外使用注冊為 allowDefinition='MachineToApplication' 的節(jié)是錯誤的2009-03-03

