将JavaScript对象/哈希传递给Handlebars帮助器?

Cha*_*son 12 javascript templating-engine handlebars.js

是否可以将JavaScript对象/哈希传递给Handlebars帮助程序调用?我想做这样的事情:

<label>Label here</label>
{{#textField {'id':'text_field_1', 'class':'some-class', size:30} }}{{/textField}}
<p>Help text here.</p>
Run Code Online (Sandbox Code Playgroud)

这是一个jsFiddle.目前它产生以下错误

Uncaught Error: Parse error on line 3:
...bel>  {{#textField {'id':'text_field_1'
----------------------^
Expecting 'CLOSE', 'CLOSE_UNESCAPED', 'STRING', 'INTEGER', 'BOOLEAN', 'ID', 'DATA', 'SEP', got 'INVALID' 
Run Code Online (Sandbox Code Playgroud)

或者,我可能会这样做并拆分',',但我不喜欢语法:

{{#textField "'id'='text_field_1','class'='some-class',size=30"}}{{/textField}}
Run Code Online (Sandbox Code Playgroud)

注意:我特别不希望将数据/属性(id,类,大小等)作为JSON对象传递给template()方法.我想要模板中的所有内容.

Cha*_*son 14

解决了.我这样做了:

帮手:

Handlebars.registerHelper('textField', function(options) {
    var attributes = [];

    for (var attributeName in options.hash) {
      attributes.push(attributeName + '="' + options.hash[attributeName] + '"');
    }

    return new Handlebars.SafeString('<input type="text" ' + attributes.join(' ') + ' />');
});
Run Code Online (Sandbox Code Playgroud)

和模板:

<label>Label here</label>
{{textField id="text_field_1" class="some-class" size="30" data-something="data value"}}
<p>Help text here.</p>
Run Code Online (Sandbox Code Playgroud)

根据文档(页面底部),您可以将可变数量的参数传递给辅助方法,并且它们将在options.hash中可用(假设"options"是辅助方法的参数).而且这也很好,你可以使用命名参数,参数顺序无关紧要.


use*_*r10 11

我发现了另一种传递物体的最佳方法.

模板:

{{textField dataAttribs='{"text":"Hello", "class": "text-field"}'}}
Run Code Online (Sandbox Code Playgroud)

帮手:

Handlebars.registerHelper('textField', function(options) {
    var attribs;

    attribs = JSON.parse(options.hash.dataAttribs);
    console.log(attribs.text + " -- " + attribs.class);
    ......
    ........
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle为此