Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass variables to a mustache partial

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>
like image 855
Morgan O'Neal Avatar asked Mar 27 '13 18:03

Morgan O'Neal


3 Answers

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}}
like image 66
Ohad Sadan Avatar answered Jan 05 '23 01:01

Ohad Sadan


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/

like image 28
Wildfire Avatar answered Jan 04 '23 23:01

Wildfire


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.

like image 33
U-ways Avatar answered Jan 05 '23 01:01

U-ways