利用模板生成html頁面(NVelocity)


公司的網站需要有些新聞,每次的新聞格式都是一樣的,而不想每次都查詢操作,所以想把這些新聞的頁面保存成靜態的html,之后搜索了下就找到了這個模板引擎,當然其他的模板引擎可以的,例如:Razor,自己寫的手動替換等。NVelocity是Apache Jakarta Velocity中的一個優秀項目,有java版的(Velocity),.NET版(NVelocity),它是非常簡單,易於學習和可擴展的模板引擎,並且支持.NET Core.

在NVelocity中對變量的引用都是以$開頭,加上變量名稱,當使用 ! 時表示為空字符串,語法都是#開頭。

語法

1. 賦值指令#set

#set($book.title="test")

2.條件指令#if   if/elseif/else

#if($books.Total>1)
 $books.Total
#else 
 沒有數據
#end

3.循環指令 #foreach

#foreach($book in $books)
$book.Title 
#end

高級foreach
#foreach($i in $items)
#each
每次【循環】顯示的文本
#before
每次【循環前】顯示的文本
#after
每次【循環后】顯示的文本
#between
每【兩次】【循環】顯示的文本
#odd
奇數顯示
#even
偶數顯示
#nodata
空或者沒有數據
#beforeall
循環之前顯示
#afterall
循環之后顯示
#end

4.引用靜態資源指令 #include

#include('jquery.js') 會把當前js當作當前流插入到內容中

5.引用並解析資源指令 #parse

#parse('temo.js');
與#include不同的是,假如temp.js中有NVelocity的指令,變量進行處理,並把結果插入到當前流中;

6. 雙數執行 #even   odd

#foreach(book in $books)
     #even
     <p>雙行:$book.Title</p>
     #odd
     <p>單行:$book.Title</p>
#end

7. 關系運算符

AND、OR 和 NOT 操作符,分別對應&&、||和! 
#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>
    <meta charset="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);

    // 設置變量
    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. 程序調用

News news = new News() { Title = $"{DateTime.Now} 新聞", Desc = "新聞的描述信息", Content = "新聞的詳細內容", 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>
        新聞的詳細內容
    </div>
</body>
</html>

總結

NVelocity可以應用在很多地方,不僅僅局限於生成html頁,也可以是郵件模板等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM