Lets say I have a mustache button partial like this
<button name="{{name}}" class="btn">{{title}}</button>
Is it possible somehow to set the title when calling the partial directly like this
<form>
....
{{> button|name=foo,title=Cancel}} {{> button|name=bar,title=Submit}}
</form>
This would make it much easier to create views instead of something like this and creating a hash for each button.
<form>
....
{{#buttons}}
{{> button}}
{{/buttons}}
</form>
I am not sure you can do that but I worked around that using mustache functions
javascript
var partial = "<div>{{value}}</div>";
var data = {some_data:[1,2,3]};
var items = {func:function (){
return function (index){
return mustache.render(partial,{value : data.some_data[index]});
}
});
mustache.render(main,items);
mustache
{{#func}}1{{/func}}
{{#func}}2{{/func}}
It's not possible to do it in plain Mustache, but it's doable in Handlebars with helpers. Handlebars is an extension of Mustache, so you can switch to it just by replacing parser library. Here's how it might look in Handlebars:
JS Helper (there are also implementations for many other languages):
Handlebars.registerHelper('button', function(title, options) {
var attrs = Em.keys(options.hash).map(function(key) {
key + '="' + options.hash[key] + '"';
}).join(" ");
return new Handlebars.SafeString(
"<button " + attrs + ">" + title + "</button>");
});
Usage in template:
{{buttton title name="name" class="class"}}
More info is available here: http://handlebarsjs.com/
No, you cannot pass variable view data directly from the template using Mustache.
However, rendering your buttons as a section using a list is a suitable alternative as of current when using Mustache:
Partial: (buttons.mst)
{{#buttons}}
<button name="{{name}}" class="btn">{{title}}</button>
{{/buttons}}
Template:
<form>
...
{{> buttons}}
</form>
View:
buttons: [
{ name: 'foo', title: 'Cancel' },
{ name: 'bar', title: 'Submit' },
]
Output:
<form>
...
<button name="foo" class="btn">Cancel</button>
<button name="bar" class="btn">Submit</button>
</form>
Which actually works quite well since if no buttons were passed, the partial won't be rendered.
Hope it helps.
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