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.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With