2012-09-09 48 views
0

是否可以在@helper的輸出上實現自定義轉換?我的觀點是在一個解決辦法,讓我有東西沿着這些路線到達:在ASP.NET MVC Razor視圖中轉換@helper的輸出

@helper RenderCombinedStylesheetsWithColorOverride(string color) 
{ 
    <link rel="stylesheet" type="text/css" href="menu.css" /> 
    <link rel="stylesheet" type="text/css" href="site.css" /> 
    <style type="text/css"> 
     * { color: @color; } 
    </style> 
} 

的轉折是在助手(RenderCombinedStylesheets ...),這暗示想什麼,我的名字在這裏做。也就是說,使用幫助器的普通HTML編碼輸出,並通過我的自定義代碼管理它。在那裏,我想分開它,然後重新組裝它,以便最終的輸出是一個<link rel="stylesheet" ... />引用生成的組合和縮小的CSS文件。

請注意,這是一個簡化的例子!實際上,有多個參數,輸出轉換不​​僅僅侷限於組合樣式表片段。我也想這樣做JavaScript代碼生成。

主要目標是要拿出東西,這將讓我申請正常剃刀模板的具體章節我的看法並射出最終輸出之前執行額外的轉換對這些部分

任何想法讚賞!

更新:我在this SO問題,這表明一個方式來完成這個偶然是通過純醇」的HtmlHelper擴展。看來我對他們的工作有不完全的理解,或者至少低估了他們的力量。我會報告實施情況。

回答

0

是的!我在我更新的問題中鏈接的帖子是現貨!這裏的解決方案:

public static class ResourceCombiningHelper 
{ 
    private static string MakeKey(string type) 
    { 
     return "CombinableResource" + (type ?? "").ToLowerInvariant(); 
    } 

    public static IHtmlString CombinableResource(this HtmlHelper helper, dynamic template, string type) 
    { 
     var key = MakeKey(type); 
     var context = helper.ViewContext.HttpContext; 
     var resources = (List<dynamic>)context.Items[key]; 

     if (resources == null) 
     { 
      resources = new List<dynamic> { template }; 
      context.Items[key] = resources; 
     } 
     else 
     { 
      resources.Add(template); 
     } 

     return new HtmlString(String.Empty); 
    } 

    public static IHtmlString RenderCombinableResources(this HtmlHelper helper, string type) 
    { 
     var key = MakeKey(type); 
     var context = helper.ViewContext.HttpContext; 
     var resources = (List<dynamic>)context.Items[key]; 

     if (resources != null) 
     { 
      foreach (var resource in resources) 
      { 
       if (resource is HelperResult) 
       { 
        // Add in-line content to combined resource here. 
       } 
       else if (resource is string) 
       { 
        // Add external reference to combined resource here. 
       } 
      } 
     } 

     // Return a single reference to the combined resource (<link>, <script>, etc.) 
    } 
} 

用法在Razor視圖:

@helper ColorOverridingStyle(string color) 
{ 
    <style type="text/css"> 
     * { color: @color; } 
    </style> 
} 

@{ var color = ViewBag.TextColor; } 
@Html.CombinableResource(Url.Content("~/Content/site.css"), "css") 
@Html.CombinableResource(Url.Content("~/Content/menu.js"), "js") 
@Html.CombinableResource(ColorOverridingStyle(color), "css") 

而且最終的HTML輸出例子:

<head> 
    <link href="/Content/combined-css.css" rel="stylesheet" type="text/css" /> 
    <script src="/Content/combined-js.js" type="text/javascript"></script> 
</head> 

的偉大工程!關閉這個小寶石的限制... :)

相關問題