在 handlebar emberjs 中动态输出每个循环内的表达式

Dynamically output the expression within each loop in handlebar emberjs

假设我有以下控制器

App.SomeController = Ember.Controller.extend({
  container: Ember.A(['one','two','three']),
  attrOne: 'Attribute One',
  attrTwo: 'Attribute Two',
  attrThree: 'Attribute Three'
});

在我的把手中,我可以循环容器数组中的每个值,但是我如何在每个循环中动态填充每个属性

{{#each data in container}}
  {{data}} // one, two, three
  {{???}} // {{attrOne}} {{attrTwo}} {{attrThree}} ??? How ???
{{/each}}

Handlebars 无法进行计算,{{#each}} 一次只能循环一个数组。因此,您 each 遍历的数组中的元素必须包含您要输出的所有数据。因此,您可以采用定义计算的 属性 的方法,其中包含您需要的数据,我们将其称为 loopData。问题是数组中的键与相应的属性字符串之间的唯一联系是 属性 的名称,其中前缀是键。所以:

// in controller
loopData: function() {
  return this.get('container') .        // take container and
    map(function(key) {                 // create array which for each key
      var attr = this.get('attr' +      // gets property name starting with 'attr'
        key.capitalize();               // and ending in the key
      return { key: key, attr: attr };  // and returns little object with key and attr
  });
}.property('container.@each')

这将创建一个类似于

的数组
[{ key: 'one', attr: 'Attribute One' }, ...]

您可以在模板中循环:

{{#each data in loopData}}
    {{data.key}} // one, two, three
    {{data.attribute}}
{{/each}}    

但是,这工作量太大,可能不是构建数据的好方法。您最好直接将基本属性定义为

container: [
    { key: 'one', attr: 'Attribute One' },
    { key: 'two', attr: 'Attribute Two' },
    { key: 'three', attr: 'Attribute Three' },
]

然后直接遍历 container 而无需创建中间数据表示。