Razor模板引擎工作原理及怎麼調用外部方法演示

工作原理:

RazorEngine引擎就是將cshtml模板文件進行了字符串的拼接,然後,再封裝爲一個程序集。。。再通過一般處理程序,進行調用。。

下面來封裝一個方法。來簡化上一節內容的操作;

1.獲得虛擬路徑;
2.從虛擬路徑中讀取cshtml模板中的內容;
3.給cshtml模板文件取一個別名字;(提高網站性能)
4. 用model替換模板中的變量;

封裝一個類

步驟:項目名字—右鍵—-添加—–RPcshtmlHelper

RPcshtmlHelper.cs

using RazorEngine;
using RazorEngine.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Web2
{
    public class RPcshtmlHelper
    {
        //弄清關係,不要懷疑工具的錯誤,檢查自己操作的問題

        //1.封裝一個方法,省去了每次都重複自己添加cacheName的麻煩
        public static string ParseRazor(HttpContext context, string csHtmlVirtualPath, object model)
        {
            //2.拿到虛擬路徑
            string fullPath = context.Server.MapPath(csHtmlVirtualPath);
            //3.讀取模板
            string cshtml = File.ReadAllText(fullPath);
            //4.給模板文件取一個別名字
            string cacheName = fullPath + File.GetLastWriteTime(fullPath);
            //5.用model替換變量
            string html = Razor.Parse(cshtml,model,cacheName);
            //6.返回模板文件內容
            return html;
        }

        //1.定義一個簡單的《靜態》方法,作爲測試,這裏的方法是在cshtml模板文件中調用的
        public static HtmlEncodedString Test1()
        {
            return new HtmlEncodedString("<input type='text' />");

        }
        // 同樣定義第二個《靜態》方法
        public static RawString Test2()
        {
            return new RawString("<input type='text' />");

        }
    }
}

定義一個模板Razor2.cshtml

<!--1.首先,在模板文件中讀取RPcshtmlHelper的命名空間-->
@using Web2

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <!--2.調用類中的測試方法Test1--Test2-->
     html標籤轉義過的   @RPcshtmlHelper.Test1()<br />
    html標籤沒有轉義過的   @RPcshtmlHelper.Test2()
    <!--3.添加一個一般處理處理程序,調用該模板文件-->
</body>
</html>

新建一個一般處理程序,調用類中封裝好的方法,來讀取模板文件cshtml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web2
{
    /// <summary>
    /// Razor2 的摘要說明
    /// </summary>
    public class Razor2 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";//1.修改爲html

            //2.調用封裝的方法ParseRazor
           string html= RPcshtmlHelper.ParseRazor(context, "~/Razor2.cshtml",null);

            //3.將轉化過的模板內容輸入到瀏覽器
            context.Response.Write(html);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

讀取結果

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章