模版引擎(NVelocity)開發

在net中用模版開發,在handler中用到了大量的html代碼。爲解決這個問題,我能夠採用模版引擎(NVelocity)進行開發。
一、首先須要將NVelocity.dll文件放入項目,其次引用。
二、配置更改,
代碼以下:css

context.Response.ContentType = "text/html";
            //1.建立Velocity 引擎(VelocityEngine)並設置屬性
            VelocityEngine vltEngine = new VelocityEngine();
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, context.Request.MapPath("~/templates"));
            vltEngine.Init();

            // 2.Velocity 上下文對象設置
            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("data", "yhb");

            // 3.建立模板
            Template vltTemplate = vltEngine.GetTemplate("photo.htm");
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            // 4.合併模板和上下文對象,輸出
            vltTemplate.Merge(vltContext, vltWriter);

            context.Response.Write(vltWriter.GetStringBuilder().ToString());

將上述代碼中須要的部分更改爲我須要的配置,1.MapPath中所放路徑爲htm所在路徑,2.vltContext.Put方法中所放爲一個鍵值對,值爲想要的信息,如datateble,list等等、、,3.在模版建立中vltEngine.GetTemplate方法中所放爲當前要用的模版htm。(file)爲以文件方式讀取。html

三、前臺的使用,
前臺代碼以下:ui

<head>
    <title>模版引擎的使用</title>
    <style type="text/css">
        img
        {
            width: 50px;
            height: 50px;
        }
        table
        {
            border: 1px solid black;
            border-collapse: collapse;
        }
        table th, table td
        {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <th>
                編號
            </th>
            <th>
                圖片
            </th>
            <th>
                支持
            </th>
            <th>
                反對
            </th>
            <th>
                分享
            </th>
            <th>
                描述
            </th>
            <th>
                做者
            </th>
        </tr>
        #foreach($jj in $jia.rows)
        <tr>
            <td>
                $!jj.id
            </td>
            <td>
                <img src="$!jj.url" />
            </td>
            <td>
                $!jj.up
            </td>
            <td>
                $!jj.down
            </td>
            <td>
                $!jj.share
            </td>
            <td>
                $!jj.Description
            </td>
            <td>
                $!jj.author
            </td>
        </tr>
        #end
    </table>
</body>

  

注意在代碼中$是一中語法,在$後面跟上vltContext.Put中建好的鍵值對的鍵就能夠訪問數據了,在NVelocity中只有foreach循環,循環開始時用#foreach結束時用#end。
$鍵的方式是取值,若是沒有該值的話,會在頁面上顯示原有樣式,用取反的方式($!鍵)這樣有值則會顯示,沒值也不會在頁面上顯示原有樣式。
當$!鍵後直接跟了一段英文或字母,則NVelocity會講這次的訪問看成一個不存在的鍵訪問,這種狀況下能夠用$!{鍵}xiaoxue的語法訪問。url

相關文章
相關標籤/搜索