[英]Pass JavaScript object/hash to Handlebars helper?
Is it possible to pass a JavaScript object/hash into a Handlebars helper call? 是否可以将JavaScript对象/哈希传递给Handlebars帮助程序调用? I'd like to do something like this: 我想做这样的事情:
<label>Label here</label>
{{#textField {'id':'text_field_1', 'class':'some-class', size:30} }}{{/textField}}
<p>Help text here.</p>
Here is a jsFiddle . 这是一个jsFiddle 。 Currently it produces the following error 目前它产生以下错误
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'
Alternatively I could probably do this and split on ',', but I am not fond of the syntax: 或者,我可能会这样做并拆分',',但我不喜欢语法:
{{#textField "'id'='text_field_1','class'='some-class',size=30"}}{{/textField}}
NOTE: I specifically do NOT want to pass data/attributes (id, class, size, etc.) into the template() method as a JSON object. 注意:我特别不希望将数据/属性(id,类,大小等)作为JSON对象传递给template()方法。 I want everything in the template. 我想要模板中的所有内容。
Solved. 解决了。 I did this: 我这样做了:
Helper: 帮手:
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(' ') + ' />');
});
And the template: 和模板:
<label>Label here</label>
{{textField id="text_field_1" class="some-class" size="30" data-something="data value"}}
<p>Help text here.</p>
Per the documentation (bottom of the page), you can pass in a variable number of parameters to a helper method, and they will be available in options.hash (assuming "options" is a parameter to your helper method). 根据文档 (页面底部),您可以将可变数量的参数传递给辅助方法,并且它们将在options.hash中可用(假设“options”是辅助方法的参数)。 And what's also nice about this is that you can use named parameters, and parameter order doesn't matter. 而且这也很好,你可以使用命名参数,参数顺序无关紧要。
I found another best way to pass objects. 我发现了另一种传递物体的最佳方法。
Template: 模板:
{{textField dataAttribs='{"text":"Hello", "class": "text-field"}'}}
Helper: 帮手:
Handlebars.registerHelper('textField', function(options) {
var attribs;
attribs = JSON.parse(options.hash.dataAttribs);
console.log(attribs.text + " -- " + attribs.class);
......
........
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.