微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

可以将 JavaScript对象/哈希传递给Handlebars帮助程序调用吗?我想做这样的事情:
<label>Label here</label>
{{#textField {'id':'text_field_1','class':'some-class',size:30} }}{{/textField}}
<p>Help text here.</p>

Here is a 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,类,大小等)作为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>

根据the documentation(页面底部),您可以将可变数量的参数传递给辅助方法,并且它们将在options.hash中可用(假设“options”是您的帮助方法的参数).还有什么也很好,你可以使用命名参数,而且参数顺序并不重要.

原文地址:https://www.jb51.cc/js/151679.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐