[英]Undefined in Handlebars helper function
I have a custom helper as given below.我有一个自定义助手,如下所示。 Somehow value of the passed params (v1, v2, v2) gets undefined.不知何故,传递的参数 (v1, v2, v2) 的值未定义。 Any pointers would be helpful.任何指针都会有所帮助。
Something.js:东西.js:
Handlebars.registerHelper('hasAccess', function(v1, v2, v3) {
console.log(v1 + ', ' + v2 + ', ' + v3); //this gives undefined
if (v1 && v2 && v3) {
return true;
}
return false;
});
and my template, as follows:和我的模板,如下:
{{#each list1}}
<span>{{this}}{{#if hasAccess value1 value2 value3}}<sup>display-something</sup>{{/if}}</span>
{{/each}}
getTemplateData() {
const value1 = true;
let value2 = true;
let value3 = false;
let list1 = [10, 20, 30];
}
I am also new to UI so any suggestion to improve the code would be appreciated.我也是 UI 新手,所以任何改进代码的建议都将不胜感激。
There are a couple of issues with your template.您的模板有几个问题。
First, #if
requires a single argument, which it will evaluate for truthiness.首先, #if
需要一个参数,它将评估其真实性。 In order to give #if
the result of the hasAccess
helper, we will need to parens to make the hasAccess
evaluation a subexpression .为了给出hasAccess
帮助器的#if
结果,我们需要使用括号使hasAccess
评估成为 子表达式。
Our template gets updated to:我们的模板更新为:
{{#if (hasAccess value1 value2 value3)}}<sup>display-something</sup>{{/if}}
This prevents Handlebars from throwing an error, but the arguments to our hasAccess
helper all have the value of undefined
.这可以防止 Handlebars 抛出错误,但是我们的hasAccess
助手的参数都具有undefined
的值。 This is because value1
, value2
and value3
are not available to the evaluation context within our #each
loop.这是因为value1
、 value2
和value3
在我们的#each
循环中对评估上下文不可用。 We will need to use paths in order to access the parent context .我们需要使用路径来访问父上下文。
Now our template becomes:现在我们的模板变成:
{{#if (hasAccess ../value1 ../value2 ../value3)}}<sup>display-something</sup>{{/if}}
Note: As value1
, value2
and value3
all belong to ourroot data context , we could alternatively do:注意:由于value1
、 value2
和value3
都属于我们的根数据上下文,我们也可以这样做:
{{#if (hasAccess @root.value1 @root.value2 @root.value3)}}<sup>display-something</sup>{{/if}}
I have created a fiddle for your reference.我创建了一个小提琴供您参考。
As for suggestions on code improvement.至于代码改进的建议。 I am of the opinion that the if (true) { return true; }
我认为if (true) { return true; }
if (true) { return true; }
style is an anti-pattern and is much more cleanly written as: if (true) { return true; }
是一种反模式,写得更简洁:
Handlebars.registerHelper('hasAccess', function(v1, v2, v3) {
return Boolean(v1 && v2 && v3);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.