2011-07-29 21 views
2

這裏是我的情況...渲染CSS剃刀引擎+啓用一個請求多個文件

public partial class CssController : Controller 
{ 
    public virtual ActionResult Merge(string[] files) 
    { 
     var builder = new StringBuilder(); 
     foreach (var file in files) 
     { 
      var pathAllowed = Server.MapPath(Url.Content("~/Content/css")); 
      var normalizeFile = Server.MapPath(Url.Content(Path.Combine("~/Content/css", file))); 
      if (normalizeFile.StartsWith(pathAllowed) == false) 
      { 
       return HttpNotFound("Path not allowed"); 
      } 

      if (System.IO.File.Exists(normalizeFile)) 
      { 
       Response.AddFileDependency(normalizeFile); 
       builder.AppendLine(System.IO.File.ReadAllText(normalizeFile)); 
      } 
     } 

     Response.Cache.VaryByParams["files"] = true; 
     Response.Cache.SetLastModifiedFromFileDependencies(); 
     Response.Cache.SetETagFromFileDependencies(); 
     Response.Cache.SetCacheability(HttpCacheability.Public); 

     var css = dotless.Core.Less.Parse(builder.ToString(), new DotlessConfiguration()); 

     return Content(css, "text/css"); 
    } 

    public string Index() 
    { 
     Response.ContentType = "text/css"; 
     return Razor.Parse(System.IO.File.ReadAllText(Server.MapPath("~/Content/css/Global.css"))); 
    } 
} 

}

現在使用的公共行動的方法來得到一個請求的所有CSS文件。還可以重新編譯並解析.less文件。那麼由於缺乏支持無編者,我們轉移到Razor來解析我們的CSS。底部字符串方法顯示我們在那裏嘗試做什麼。簡單明瞭,我怎樣才能整合這兩種方法而不會出錯。

在我們的規劃中,我們使用這個

<link rel="stylesheet" type="text/css" href="@Url.ActionLinkWithArray("Merge", "Css", new { files = new[] { "StoreManager.less" } })" /> 

拉動一個請求的所有文件。然而,當我想使用RazorEngine時,這是使用.less配置。

我希望這解釋了我需要做的事情。誰能幫忙?

回答

4

我最喜歡的解決方案是由安德魯Davey Cassette

在你_Layout.cshtml你:

<head> 
    <title>@ViewBag.Title</title> 
    @Assets.Scripts.Render() 
</head> 

,並且在任何認爲需要JavaScript:

@{ 
    ViewBag.Title = "My Page"; 
    Assets.Scripts.Reference("scripts/utils/date.js"); 
    Assets.Scripts.Reference("scripts/widgets/calendar.js"); 
} 

這將運行如下(包括Less)和所有的腳本和CSS凝結成一個單一的文件每。

這可能會或可能不會幫助,但肯定會使它變得容易。它看起來好像您正在爲您當前的問題尋找解決方案,但這絕對是一種選擇。

+0

感謝您向我展示這一點。似乎這些公用事業都是新生兒。使用html5,mvc3和實體框架4.1,我發現自己編寫了很多代碼來完成像這樣的基本系統級事情。到目前爲止,Cassette確實令人印象深刻,並且也非常積極地更新。 –

+0

是的,我最近一直在研究所有的Nu​​get項目,看看那裏有什麼。我在那裏發現了這一天。 – Buildstarted

+0

剛剛偶然發現了這個更加成熟的項目:http://clientdependency.codeplex.com/我認爲它是爲MVC2設計的,但似乎也適用於Razor。 –