Skip to content

Instantly share code, notes, and snippets.

@ctesene
Last active December 26, 2015 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctesene/7227674 to your computer and use it in GitHub Desktop.
Save ctesene/7227674 to your computer and use it in GitHub Desktop.
A Razor Html helper that will place your angular views in the body of your view. This is helpful for a number of reasons * Browsers cache angular partial views, so when you deploy to production, some users will not see the new content, as they have cached copies of the partial views. * Reduce page navigation delays by loading up front.
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace YourProject.RazorExtensions
{
public static class AngularJs
{
public static IHtmlString RenderAngularViews(this HtmlHelper helper, string relativeViewPath)
{
var actualPath = HttpContext.Current.Server.MapPath(relativeViewPath);
var templateBasePath = relativeViewPath.Replace(@"~", "").Replace(@"\", @"/");
var templates = Directory.GetFiles(actualPath);
var builder = new StringBuilder();
foreach (var template in templates)
{
var fileName = Path.GetFileName(template);
var templatePath = string.Format("{0}/{1}", templateBasePath, fileName);
var templateContents = File.ReadAllText(template);
var templateHtmlContents = new HtmlString(templateContents);
builder.AppendFormat(@"<script type='text/ng-template' id='{0}'>{1}</script>", templatePath, templateHtmlContents);
}
return new HtmlString(builder.ToString());
}
}
}
@using YourProject.RazorExtensions
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body data-ng-app="MyApp">
<div ng-view>
</div>
@Html.RenderAngularViews("~/app/views")
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment