公司的網(wǎng)站需要有些新聞,每次的新聞格式都是一樣的,而不想每次都查詢操作,所以想把這些新聞的頁面保存成靜態(tài)的html,之后搜索了下就找到了這個模板引擎,當然其他的模板引擎可以的,例如:Razor,自己寫的手動替換等。NVelocity是Apache
Jakarta
Velocity中的一個優(yōu)秀項目,有java版的(Velocity),.NET版(NVelocity),它是非常簡單,易于學(xué)習和可擴展的模板引擎,并且支持.NET
Core.
在NVelocity中對變量的引用都是以$開頭,加上變量名稱,當使用 ! 時表示為空字符串,語法都是#開頭。
語法
1. 賦值指令#set
#set($book.title="test")
2.條件指令#if? ?if/elseif/else
#if($books.Total>1) $books.Total #else 沒有數(shù)據(jù) #end
3.循環(huán)指令 #foreach
#foreach($book in $books) $book.Title #end 高級foreach #foreach($i in $items)
#each 每次【循環(huán)】顯示的文本 #before 每次【循環(huán)前】顯示的文本 #after 每次【循環(huán)后】顯示的文本 #between
每【兩次】【循環(huán)】顯示的文本 #odd 奇數(shù)顯示 #even 偶數(shù)顯示 #nodata 空或者沒有數(shù)據(jù) #beforeall 循環(huán)之前顯示 #afterall
循環(huán)之后顯示 #end
4.引用靜態(tài)資源指令 #include
#include('jquery.js') 會把當前js當作當前流插入到內(nèi)容中
5.引用并解析資源指令 #parse
#parse('temo.js'); 與#include不同的是,假如temp.js中有NVelocity的指令,變量進行處理,并把結(jié)果插入到當前流中;
6. 雙數(shù)執(zhí)行 #even? ?odd
#foreach(book in $books) #even <p>雙行:$book.Title</p> #odd <p>單行:$book.Title</p>
#end
7. 關(guān)系運算符
AND、OR 和 NOT 操作符,分別對應(yīng)&&、||和! #if($foo && $bar) #end
C#例子
1.Nuget中引用NVelocity
2.編寫模板頁(Hellovelocity.vm,也可以是Hellovelocity.html等任意的名稱后綴)
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <
metacharset="utf-8" /> <title>$news.Title</title> </head> <body> <h3>$news.Title
</h3> <div> <span>$news.Desc</span> </div> <div> $news.Content </div> </body> </
html>
3.編寫后臺程序
public static string TransformBooksToHtml(News news, string
resourceTemplateName) {// 初始化模板引擎 VelocityEngine ve = new VelocityEngine();
ve.Init();// 獲取模板文件 Template t = ve.GetTemplate(resourceTemplateName); // 設(shè)置變量
VelocityContext ctx =new VelocityContext(); ctx.Put("news", news); // 輸出
StringWriter sw =new StringWriter(); t.Merge(ctx, sw); string message =
sw.ToString(); sw.Dispose(); File.WriteAllText($@"{DateTime.Now.ToString("
yyyy-MM-dd-HH-mm-ss")}.html", sw.ToString());//生成文件的路徑可以自由選擇 return message; }
4. 程序調(diào)用
News news = new News() { Title = $"{DateTime.Now} 新聞", Desc = "新聞的描述信息",
Content ="新聞的詳細內(nèi)容", CreateTime = DateTime.Now };
Console.WriteLine(MyNVelocity.TransformBooksToHtml(news,@"
/NVelocityTest/Hellovelocity.html"));//這里的模板路徑是NVelocityTest目錄下的,可以任意
5. 查看生成的文件
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head>
<meta charset="utf-8" /> <title>2019/08/05 14:20:14 新聞</title> </head> <body>
<h3>2019/08/05 14:20:14 新聞</h3> <div> <span>新聞的描述信息</span> </div> <div> 新聞的詳細內(nèi)容
</div> </body> </html>
總結(jié)
NVelocity可以應(yīng)用在很多地方,不僅僅局限于生成html頁,也可以是郵件模板等。
熱門工具 換一換