Mvc 模板化的Razor引擎委託

來源:互聯網
上載者:User

標籤:

  最近在研究NopCommerce,它後台用的富文字編輯器可根據語言庫載入不同語言的編輯器,其中用到了模板化Razor引擎委託,參考這兒

  廢話不多說,直接上代碼。

 1 public static class HtmlExtensions 2     { 3         public static HelperResult ToList<T>(this IEnumerable<T> items, Func<T, HelperResult> template) 4         { 5             return new HelperResult(writer => 6             { 7                 foreach (var item in items) 8                 { 9                     template(item).WriteTo(writer);10                 }11             });12         }13     }

  方法 ToList<T>拓展了IEnumerable<T>,並傳遞一個Fun<T,out result>參數,Fun中result類型為 HelperResult,HelperResult中有ToHtmlString()方法,可把它轉為string字串, 在方法內部new HelperResult(),在建構函式內將模板產生的html寫到HelperResult中。

  在cshtml檔案中調用的代碼如下:

@{    var items = new[] { "tom", "kluas", "jerry" };}<ul>    @items.ToList(@<li>@item</li>)</ul>

  產生的html代碼如下:

<ul>    <li>tom</li>    <li>kluas</li>    <li>jerry</li></ul>

  調用 @items.ToList(@<li>@item</li>),T為string, @<li>@item</li>為模板,@item為模板中使用的參數,也是ToList<T>方法中foreach迴圈傳遞給模板檔案的參數,最終產生3條<li>。

Mvc 模板化的Razor引擎委託

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.