Last active
December 26, 2015 22:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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