【发布时间】:2018-01-29 15:47:08
【问题描述】:
我已经看到了很多关于如何访问循环内属于父上下文的变量的示例。但是,我不仅需要访问变量,还需要更改/更新它。
正如您在下面看到的,我有一个设置变量的自定义助手,但是当我尝试在循环内更改该变量时,它不起作用。有没有办法让它工作?
请看看这个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 jquery html handlebars.js handlebarshelper