NVelocity 1.1、StringTemplate 3.2和ASP.NET的ASPX頁面做了個性能測試對比,對比結果如下: 結果就是,在2臺不同的機器上,ASPX:StringTemplate:NVelocity分別爲1.00:8.53:1.61和 1.00:7.34:1.71,StringTemplate的性能最弱,NVelocity有點接近ASPX的解析效率。
我喜歡在Asp.Net MVC中使用NVelocity View Engine的一個很重要的理由就是:NVleocity簡潔易用的語法。幾乎使用#set,#if,#foreach就可以構成完整的應用,下面就介紹一下NVelocity中的語法及常用指令。
NVelocity常用語法指令
默認情況下,NVelocity解析是不分大小寫的,當然可以通過設置runtime.strict.math=true,採用嚴格解析模式。
對變量的引用:$ [ ! ][ { ][ a..z, A..Z ][ a..z, A..Z, 0..9, -, _ ][ } ]。
在NVelocity中,對變量的引用都是以$開頭加上變量名稱。當使用!時表示當此變量值爲空時,顯示空字符串。比如當$article爲空,那會顯示“$article“,而$!article會顯示爲“”。{}爲變量名稱限定,有時候變量名稱後會有字符串,這是就需要用到{}了。比如$articleshow,想引用$article,這時只要修改爲${article}就可以。其實,NVelocity對整個模板解析後都會變成這種模式。
對屬性的引用:$ [ { ][ a..z, A..Z ][ a..z, A..Z, 0..9, -, _ ]* .[a..z, A..Z ][ a..z, A-Z, 0..9, -, _ ]* [ } ] 。
例如$article.Title或者${article.Title}。
對方法的引用:$ [ { ][ a..z, A..Z ][ a..z, A..Z, 0..9, -, _ ]* .[ a..z, A..Z ][ a..z, A..Z, 0..9, -, _ ]*( [ optional parameter list... ] ) [ } ]。
例如:$article.GetListByTitle('nvelocity')或${article.GetListByTitle('nvelocity')}。其實對對象的屬性值也可以用$article.get_Title()獲得。
賦值指令#set:# [ { ] set [ } ] ( $ref = [ ", ' ]arg[ ", ' ] )。
例如:$article.Title='NVelocity',$$article.Categories=[1,2,3],當然右側也可以使用複雜的表達式:$article.Title=$otherArticle.Title.SubString(0,3),算術表達式:$article.Page=4/3等等。屬性賦值也可以用$article.set_Title('NVelocity')。
條件指令#if:# [ { ] if [ } ] ( [condition] ) [output] [ # [ { ] elseif [ } ] ( [condition] ) [output] ]* [ # [ { ] else [ } ] [output] ] # [ { ] end [ } ] 。
條件可以是返回bool的複查表達式。例如:#if($article.Total>1) $article.Title #else 沒有數據 #end。
循環指令#foreach:# [ { ] foreach [ } ] ($refinarg)statement# [ { ] end [ } ]。
例如:#foreach($article in $articles) $article.Title #end。
引用靜態資源指令#include:# [ { ] include [ } ] ( arg[ arg2 ... argn] )。
例如:#include('tmp.js'),會把tmp.js文件內容插入當前流。當然可以使用表達式:#include($article.Url)。
引用並解析資源指令#parse:# [ { ] parse [ } ] ( arg )。
例如:#parse('tmp.js'),與#include不同是,假如tmp.js文件中有NVelocity的指令,變量會進行處理,並把結果插入到當前流。
停止指令stop:# [ { ] stop [ } ] 。
當NVelocity解析到此指令時,會停止解析過程。一般用戶調試。
計算指令#evaluate:# [ { ] evaluate [ } ] ( arg )。
例如:#evaluate('$article.Title'),會在當前輸出$article.Title
應用方法:
先引入以下名稱空間:
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
第一步:創建一個VelocityEngine的實例
VelocityEngine velocity = new VelocityEngine(); //也可以使用帶參構造函數直接實例。
ExtendedProperties props = new ExtendedProperties();
velocity.Init(props);
第二步:加載模板文件
這時通過的是Template類,並使用VelocityEngine的GetTemplate方法加載模板
Template template = velocity.GetTemplate(@"path/to/myfirsttemplate.vm");
第三步:整合模板
VelocityContext context = new VelocityContext();
context.Put("from", "somewhere");
context.Put("to", "someone");
context.Put("subject", "Welcome to NVelocity");
context.Put("customer", new Customer("John Doe") );
第四步:創建一個IO流來輸出模板內容。推薦使用StringWriter(因爲template中以string形式存放)
StringWriter writer = new StringWriter();
template.Merge(context, writer);
Response.Write(writer.ToString());