gpt4 book ai didi

node.js - 从handlebars中引用 'this',handlebars-helper inArray block 助手中的每个助手

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:45 24 4
gpt4 key购买 nike

我正在使用 Node.js、express、handlebarshandlebars-helpers .

使用 res.render() 时,我将两个对象传递给我的 Handlebars 模板,对象如下:

var searchParams = {a: ['Apples']}
var searchFields = {a: ['Apples', 'Pears', 'Oranges']}

然后我希望使用 searchFields 在页面上创建复选框。当复选框变量位于相应的 searchParams 变量内时,我希望默认情况下选中该复选框。

我正在尝试使用 handlebars-helpers辅助函数inArray使用模板中的以下内容来实现此目的:

<form>
{{#each searchFields.a}}
<label>
<input name="only_a_test" value="{{this}}" type="checkbox"
{{#inArray searchParams.a this}}
checked
{{else}}
{{/inArray}}
>
{{this}}
</label>
{{/each}}
</form>

但是这会引发错误:

无法读取未定义的属性“长度”

TypeError: .../web/views/search.hbs: Cannot read property 'length' of undefined
at Object.indexOf (.../web/node_modules/handlebars-utils/index.js:82:31)
at String.helpers.inArray (.../web/node_modules/handlebars-helpers/lib/array.js:225:26)
at eval (eval at createFunctionContext (.../web/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:10:91)
at Object.prog [as inverse] (.../web/node_modules/handlebars/dist/cjs/handlebars/runtime.js:219:12)
at Object.utils.value (.../web/node_modules/handlebars-utils/index.js:237:50)
at String.helpers.eq (.../web/node_modules/handlebars-helpers/lib/comparison.js:170:15)
at eval (eval at createFunctionContext (.../web/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:5:84)
at prog (.../web/node_modules/handlebars/dist/cjs/handlebars/runtime.js:219:12)
at execIteration (.../web/node_modules/handlebars/dist/cjs/handlebars/helpers/each.js:51:19)
at Object.<anonymous> (.../web/node_modules/handlebars/dist/cjs/handlebars/helpers/each.js:61:13)

我不太明白发生了什么,我怀疑在 inArray block 帮助器中使用 this 存在问题 - 它可能没有看到底层字符串?

最佳答案

作为另一种方法,您可以考虑编写自己的自定义“Handlebars” 助手'如下,

Handlebars.registerHelper("isInArray", function(array, value) {
if (array.indexOf(value) != -1) {
return "checked";
}
});

Or an optimised way

Handlebars.registerHelper("isInArray", function(array, value) {
return array.indexOf(value) != -1 ? 'checked' : '';
});

并在模板文件中将其命名为,

<input name="only_a_test" value="{{this}}" type="checkbox" {{isInArray ../b this}}>

PEN 。希望这会有所帮助。

关于node.js - 从handlebars中引用 'this',handlebars-helper inArray block 助手中的每个助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48835497/

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