Is it possible to pass variables to a mustache partial

大城市里の小女人 提交于 2019-12-10 12:36:27

问题


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>

回答1:


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}}



回答2:


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/




回答3:


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.



来源:https://stackoverflow.com/questions/15667011/is-it-possible-to-pass-variables-to-a-mustache-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!