将JavaScript对象/哈希传递给Handlebars助手

Pass JavaScript object/hash to Handlebars helper?

本文关键字:Handlebars 助手 哈希传 JavaScript 对象      更新时间:2023-09-26

是否可以将JavaScript对象/哈希传递到Handlebars助手调用中?我想做这样的事情:

<label>Label here</label>
{{#textField {'id':'text_field_1', 'class':'some-class', size:30} }}{{/textField}}
<p>Help text here.</p>

这是一个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' 

或者,我可能会这样做,然后拆分",",但我不喜欢语法:

{{#textField "'id'='text_field_1','class'='some-class',size=30"}}{{/textField}}

注意:我特别不想将数据/属性(id、class、size等)作为JSON对象传递到template()方法中。我想要模板中的所有内容。

已解决。我做到了:

助手:

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(' ') + ' />');
});

模板:

<label>Label here</label>
{{textField id="text_field_1" class="some-class" size="30" data-something="data value"}}
<p>Help text here.</p>

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

我找到了另一种传递对象的最佳方式。

模板:

{{textField dataAttribs='{"text":"Hello", "class": "text-field"}'}}

助手:

Handlebars.registerHelper('textField', function(options) {
    var attribs;
    attribs = JSON.parse(options.hash.dataAttribs);
    console.log(attribs.text + " -- " + attribs.class);
    ......
    ........
});

此的JSFiddle