将JavaScript对象/哈希传递给Handlebars helper? [英] Pass JavaScript object/hash to Handlebars helper?
问题描述
是否可以将JavaScript对象/散列传递给Handlebars帮助器调用?我想这样做:
< label>在此标签< / label>
{{#textField {'id':'text_field_1','class':'some-class',size:30}}} {{/ textField}}
< p>帮助文本< / p为H.
这是一个jsFiddle 。目前它会产生以下错误:
未捕获错误:第3行解析错误:
... bel> {{#textField {'id':'text_field_1'
---------------------- ^
期待'CLOSE','CLOSE_UNESCAPED ','STRING','INTEGER','BOOLEAN','ID','DATA','SEP','无效'
另外,我可以做这个并分割'',但我不喜欢语法:
{{#textField''id'='text_field_1','class'='some-class',size = 30}} {{/ textField}}
注意:我特别不希望将数据/属性(id,class,size等)作为JSON传递给template()方法目的。我希望模板中的所有内容。
解决方案解决方案。我做到了这一点:
助手:
Handlebars.registerHelper(' textField',函数(选项){
var attributes = [];
(options.hash中的var attributeName){
attributes.push(attributeName +'='' + options.hash [attributeName] +''');
}
return new Handlebars.SafeString('< input type =text'+ attributes.join('') +'/>');
});
以及模板:
< label>标签在此处< / label>
{{textField id =text_field_1class =some-classsize =30data-something =data value}}
< p>帮助文字在这里< / p> ;
根据文档(页面底部),您可以将可变数量的参数传递给helper方法,并且它们将在options.hash中可用(假定options是您的helper方法的参数)。还有一点很好,你可以使用命名参数,参数顺序无关紧要。
Is it possible to pass a JavaScript object/hash into a Handlebars helper call? 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. 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. 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). And what's also nice about this is that you can use named parameters, and parameter order doesn't matter.
这篇关于将JavaScript对象/哈希传递给Handlebars helper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!