Sharing mustache/nustache templates between server and client. ASP.NET MVC
Well, I`ve made something, that works, maybe somebody will come up with better solution. Here it is:
Extenstion for @Html helper:
public static class ViewExtensions{ public static IHtmlString RenderRawContent(this HtmlHelper helper, string serverPath) { string filePath = HttpContext.Current.Server.MapPath(serverPath); //load from file StreamReader streamReader = File.OpenText(filePath); string markup = streamReader.ReadToEnd(); streamReader.Close(); return new HtmlString(markup); }}
And in Razor main view for Index page
@using MyProject.Helpers;<script type="text/template" id="person_template"> @Html.RenderRawContent("~/Templates/Person.mustache")</script>
You'll likely want to expose a new controller that can return your partial view content. E.g.:
public class TemplateController : Controller{ public PartialViewResult Get(string name) { return PartialView(name); }}
With that, and a route:
routes.MapRoute("Templates", "templates/{name}", new { controller = "Template", action = "Get" });
I can then call from the client (in this example I am using jQuery):
var model = { name: "Matt" };$.ajax({ url: "/templates/person", success: function(r) { var html = Mustache.render(r, model); $("body").append(html); }});
Name the file Person.mustache.cshtml
, and in Index.cshtml
:
<script type="text/template" id="person_template"> @Html.Partial("Person.mustache")<script type="text/template" id="person_template">
There's no need to write a helper to serve a file when the framework does that for you.