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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18085301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:41:13  来源:igfitidea点击:

Pass JavaScript object/hash to Handlebars helper?

javascripthandlebars.jstemplating-engine

提问by Chad Johnson

Is it possible to pass a JavaScript object/hash into a Handlebars helper call? I'd like to do something like this:

是否可以将 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. Currently it produces the following error

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

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.

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

回答by Chad Johnson

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.

根据文档(页面底部),您可以将可变数量的参数传递给辅助方法,它们将在 options.hash 中可用(假设“选项”是您的辅助方法的参数)。这样做的另一个好处是您可以使用命名参数,并且参数顺序无关紧要。

回答by user10

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);
    ......
    ........
});

JSFiddle for this

JSFiddle为此