我见过很多关于如何访问属于循环内父上下文的变量的示例。但是,我不仅需要访问变量,还需要更改/更新它。
正如您在下面看到的,我有一个设置变量的自定义助手,但是当我尝试在循环内更改该变量时,它不起作用。有没有办法让它发挥作用?
请看这个 jsFiddle .
模板
{{setVarWithName "test" "hello"}}
{{#each questions}}
<h3>{{title}}</h3>
<p>before update: {{../test}}</p>
{{setVarWithName "test" "goodbye"}}
<p>after update: {{../test}}</p>
<hr />
{{/each}}
Handlebars init with helper
var source = $("#template").html();
var template = Handlebars.compile(source);
var data = {
"questions": [
{"title": "Question 1"},
{"title": "Question 2"}
]
};
Handlebars.registerHelper('setVarWithName', function (name, value) {
this[name] = value;
return '';
});
$('body').append(template(data));
最佳答案
就像 JavaScript 中经常出现的那样,答案是作用域。基本上,this
在你的助手里面 setVarWithName
没有指向你的 data
在 {{#each}}
中使用时的变量循环,但它确实指向 question[@index]
.你需要做什么:
var source = $("#template").html();
var template = Handlebars.compile(source);
var data = {
"questions": [
{"title": "Question 1"},
{"title": "Question 2"}
]
};
Handlebars.registerHelper('setVarWithName', function (name, value) {
data[name] = value; // changed from this to data
return '';
});
$('body').append(template(data));
查看我的工作 fiddle .我添加了 {{s}}
打印渲染的助手 this
放入模板中以提高可读性。
关于javascript - 从循环内的父上下文更改/更新 Handlebars JS 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505033/