C# MVC如何捆绑类型为“的html模板”;text/html“;?
我有一些JS组件使用的一系列模板文件(*.html)。我不想让这些JS组件在加载时将模板写入DOM,而是想将它们像脚本一样捆绑在一起,并让客户端单独下载。这种方式应该更快(客户端),允许缓存(更少的往返),并且更具可读性(模板不必存储在破坏突出显示/智能感知的JS字符串中) 如何才能做到这一点。 使用BundleTransformer[和胡须模板]或把手[ 二,。 [有角度的例子,但你可以启发很多] 我并不是说这是你案例的最佳方法,但我不能把它当作一个评论 下面是OP将其捆绑包存储在$templateCache中的示例。Angular有一个templateCache对象,该对象存储迄今为止加载的所有模板。它还允许您将模板预加载到模板缓存中 创建BundleTransform类,正如他所做的:C# MVC如何捆绑类型为“的html模板”;text/html“;?,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我有一些JS组件使用的一系列模板文件(*.html)。我不想让这些JS组件在加载时将模板写入DOM,而是想将它们像脚本一样捆绑在一起,并让客户端单独下载。这种方式应该更快(客户端),允许缓存(更少的往返),并且更具可读性(模板不必存储在破坏突出显示/智能感知的JS字符串中) 如何才能做到这一点。 使用BundleTransformer[和胡须模板]或把手[ 二,。 [有角度的例子,但你可以启发很多] 我并不是说这是你案例的最佳方法,但我不能把它当作一个评论 下面是OP将其捆绑包存储在$templ
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";
}
}
但是你可以把模板存放在你想要的地方[我不知道你想把它们存放在哪里]
然后创建一个包
public class PartialsBundle : Bundle
{
public PartialsBundle(string moduleName, string virtualPath)
: base(virtualPath, new[] { new PartialsTransform(moduleName) })
{
}
}
您可以像脚本包或样式包一样使用它
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对象强制Angular在需要时不动态下载模板
进一步阅读此处:您是否使用angular?我给您留下了一个答案,您可以从中得到启发。我不知道任何其他方法,因为我没有使用任何其他方法。但如果您稍微更改一下,它可能会适用。我已使用BundleTransformer的另一种方法更新了我的答案,该方法支持胡须和把手rs