在@root上下文中如何访问@root变量

时间:2019-04-12 00:21:28

标签: javascript handlebars.js

说我有一个名为array的对象数组,其结构如下:

mainObject: {
  array1: [1,2],
  array2: ['x','y']
}

我的第一步是遍历array1

{{#each mainObject.array1}}
  {{this}}
{{/each}}

哪个会产生1,2

的结果

我想做的是使用循环的当前索引来串联访问array2。因此,当我从1访问array1时,我想获取0的索引值并将其传递给array2以访问'x',然后继续循环的下一个迭代(索引1),我将从2获得array1,从'y'获得array2

我尝试了以下方法,但没有成功:

{{#each mainObject.array1}}
  {{this}}
  {{@root.mainObject.array2.[@index]}}
{{/each}}
{{#each mainObject.array1}}
  {{this}}
  {{../mainObject.array2.[@index]}}
{{/each}}
{{#each mainObject.array1}}
  {{this}}
  {{setVariable "refIndex" @index}} // This is a helper that I use which typically works
  {{../mainObject.array2.[@root.refIndex]}}
{{#each mainObject.array1}}
  {{this}}
  {{setVariable "refIndex" @index}} // Same helper from above
  {{@root.mainObject.array2.[@root.refIndex]}}

作为参考,这是我上面引用的setVariable助手的代码:

hbs.registerHelper('setVariable', function(varName, varValue, options) {
    options.data.root[varName] = varValue;
});

0 个答案:

没有答案
相关问题