我有一系列由一些JS組件使用的模板文件(* .html)。我不想讓這些JS組件在加載時將模板寫入DOM,而想將它們像腳本一樣捆綁在一起,並讓它們分別由客戶端下載。這種方式應該更快(客戶端),允許緩存(更少的往返行程),並且更具可讀性(模板不必存儲在突破高亮/智能感知的JS字符串中)。MVC如何捆綁「text/html」類型的html模板?
這是如何實現的?
我有一系列由一些JS組件使用的模板文件(* .html)。我不想讓這些JS組件在加載時將模板寫入DOM,而想將它們像腳本一樣捆綁在一起,並讓它們分別由客戶端下載。這種方式應該更快(客戶端),允許緩存(更少的往返行程),並且更具可讀性(模板不必存儲在突破高亮/智能感知的JS字符串中)。MVC如何捆綁「text/html」類型的html模板?
這是如何實現的?
一 使用BundleTransformer [http://bundletransformer.codeplex.com/]和小鬍子模板[https://mustache.github.io/]或把手[http://handlebarsjs.com/]
II。 [角度的例子,但你可以激發很多]
我不是說這是你的情況的最佳方法,但我不能像評論一樣離開它。
下面是OP將其包存儲在$ templateCache中的示例。 Angular有一個templateCache對象,它存儲了迄今爲止加載的所有模板。它還可以讓您將模板預加載到模板緩存中。
創建BundleTransform類,像他那樣:
public class PartialsTransform : IBundleTransform
{
private readonly string _moduleName;
public PartialsTransform(string moduleName)
{
_moduleName = moduleName;
}
public void Process(BundleContext context, BundleResponse response)
{
var strBundleResponse = new StringBuilder();
// Javascript module for Angular that uses templateCache
strBundleResponse.AppendFormat(
@"angular.module('{0}').run(['$templateCache',function(t){{",
_moduleName);
foreach (var file in response.Files)
{
// Get the partial page, remove line feeds and escape quotes
var content = File.ReadAllText(file.FullName)
.Replace("\r\n", "").Replace("'", "\\'");
// Create insert statement with template
strBundleResponse.AppendFormat(
@"t.put('partials/{0}','{1}');", file.Name, content);
}
strBundleResponse.Append(@"}]);");
response.Files = new FileInfo[] {};
response.Content = strBundleResponse.ToString();
response.ContentType = "text/javascript";
}
}
但你可以存儲你想要[我不知道你要存儲這些]模板。
然後創建一個Bundle。
public class PartialsBundle : Bundle
{
public PartialsBundle(string moduleName, string virtualPath)
: base(virtualPath, new[] { new PartialsTransform(moduleName) })
{
}
}
而且您可以像ScriptBundle或StyleBundle一樣使用它。
bundles.Add(new PartialsBundle("testSPA", "~/bundles/partials").Include(
"~/Partials/nav-bar.html",
"~/Partials/home-page.html",
"~/Partials/investment-filter.html",
"~/Partials/investments-component.html",
"~/Partials/sector-component.html",
"~/Partials/transactions-component.html"));
和渲染這樣的:@Scripts.Render("~/bundles/partials")
在生產中轉化在此:
<script src="/bundles/partials?v=dq0i_tF8ogDVZ0X69xyBCdV2O2Qr3nCu0iVsatAzhq41"></script>
這傢伙是使用$ templateCache對象迫使角不能動態地下載模板在需要的時候。
在這裏進一步閱讀:http://blog.scottlogic.com/2014/08/18/asp-angular-optimisation.html
你使用的是角? –
@RazvanDumitru No. – Slight
我給你留下了一個你可以從中得到啓發的答案。我不知道任何其他方法,因爲我沒有使用任何其他方法。但是如果你稍微改變它,可能它會適合。 –