I have a AJAX that send JSON to client, so it can render a Mustache template on the client side. The Mustache template has a partial. Everything goes fine. I'll borrow the example from here
Sample 11: Partials (JS Version of Mustache)
var data = { depts: [
{ name: "Engineering",
employees: [
{firstName: "Christophe", lastName: "Coenraets"},
{firstName: "John", lastName: "Smith"}]
},
{ name: "Sales",
employees: [
{firstName: "Paula", lastName: "Taylor"},
{firstName: "Lisa", lastName: "Jones"}]
}]
};
var tpl = "{{#depts}}<h1>{{name}}</h1>" +
"<ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";
var partials = {employee: "<li>{{firstName}} {{lastName}}</li>"};
var html = Mustache.render(tpl, data, partials);
$('#sampleArea').html(html);
As you can see in the call to Mustache.render
, there is a 3rd argument that you can pass PARTIALS, works great in JS.
I need to do the exactly same thing in Ruby, but the problem is, in Ruby Mustache, the 3rd argument doesn't exist . I've seen the Mustache source and I've debugged it, it has something to do with the "context" of Mustache, but could not figure it out how to pass a PARTIAL like in the JS version of Mustache.
I've tried:
Mustache.render( mytemplate, { data: myjson, partial: mypartial })
but it doesn't render myjson
In the Ruby implementation, partials are loaded from the filesystem by Mustache.partial
, which, by default, checks for a file named mypartial.mustache
in the current directory. You can override the default behavior by subclassing Mustache for your own specific needs:
class MyMustache < Mustache
PARTIALS = {
employee: "<li>{{firstName}} {{lastName}}</li>"
}
def partial(name)
PARTIALS[name.to_sym]
end
end
puts MyMustache.render(tpl, data)
The Ruby implementation is remarkably well documented, but mostly in the source comments. Check it out for more info :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.