gpt4 book ai didi

javascript - 在 Handlebar 模板中的 if 条件下使用数组键的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-03 10:18:39 25 4
gpt4 key购买 nike

我正在使用这个注册助手:

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {

switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
case '&&':
return (v1 && v2) ? options.fn(this) : options.inverse(this);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});

并循环数据选项,它们是:

var dataOptions = {
number: "Number",
string: "String",
bool: "Boolean",
none: "Null/None"
}

我只想标记选中的选项,如下所示:

{{#each dataOptions}}
<option value="{{@key}}"{{#ifCond @key '==' element.data}} checked="checked"{{/ifCond}}>{{this}}</option>
{{/each}}

但是条件似乎不起作用。我想知道这是因为在 helper 中使用了 @key 还是什么?

最佳答案

看起来你的dataOptions是一个数组。 @key 用于对象,@index 用于数组,尝试将代码更改为:

{{#each dataOptions}}
<option value="{{@index}}"{{#ifCond @index '==' element.data}} checked="checked"{{/ifCond}}>{{this}}</option>
{{/each}}

还指出 each block 将创建一个新范围,因此您可能需要使用 ../element.data 引用 element.data >

<小时/>

为了进行调试,您可以添加 console.log(arguments); 作为自定义帮助函数中的第一行:

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {

console.log(arguments); // <-- could also use `debugger` if you want a breakpoint when the helper is called.

switch (operator) {
// ...

关于javascript - 在 Handlebar 模板中的 if 条件下使用数组键的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29743737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com