Sharing mustache / nustache patterns between server and client. ASP.NET MVC

I am using mustache.js on the client and Nustache in an ASP.NET MVC3 project.

I have a Person.mustache template in the View folder on the server, which I use as follows:

 @Html.Partial("Person") 

from the main Razor view ( Index.cshtml ).

But how can I pass it on to the client? The browser does not have access to the Views folder to get the original contents of the template. Somehow, I should have a way to enable the HTML output of the Person.mustache template on the server. If I require it from a Razor view, it will compile it, since this is the usual server template mechanism.

Please can anyone give any ideas? Thanks.

+7
source share
3 answers

Well, I did something, it works, maybe someone will come up with a better solution. Here he 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 the Razor main view for the Index page

 @using MyProject.Helpers; <script type="text/template" id="person_template"> @Html.RenderRawContent("~/Templates/Person.mustache") </script> 
+3
source

You will probably want to open a new controller that can return your partial content. For example:.

 public class TemplateController : Controller { public PartialViewResult Get(string name) { return PartialView(name); } } 

With this and the route:

 routes.MapRoute("Templates", "templates/{name}", new { controller = "Template", action = "Get" }); 

Then I can 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); } }); 
+1
source

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 is no need to write an assistant to work with the file when the framework does this for you.

0
source

All Articles