Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I`m using mustache.js on client and Nustache in ASP.NET MVC3 project.

I have Person.mustache template in a View folder on server, which I use like this:

@Html.Partial("Person")

from Razor main view (Index.cshtml).

But how can I transfer it to client? Browser has no access to Views folder to get raw content of a template. Somehow I must have a way to include to output HTML raw text of Person.mustache template on server. If I require it from Razor view, it compiles it, since it is normal server template engine.

Please anyone can give any ideas? Thanks.

like image 986
Roman Avatar asked Mar 14 '12 12:03

Roman


2 Answers

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>
like image 92
Roman Avatar answered Nov 09 '22 05:11

Roman


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);
  }
});
like image 29
Matthew Abbott Avatar answered Nov 09 '22 04:11

Matthew Abbott