在块帮助器中使用Ember的Handlebars #each helper,将数组切成块

时间:2013-12-26 23:10:26

标签: javascript ember.js handlebars.js

我正在尝试将ArrayController的{​​{1}}切成块(用于表示目的)。在每个块中,我想迭代这些项目,以便正确地渲染所有内容。

我尝试通过编写content Handlebars块助手来完成此操作,这似乎有效。但是,当我尝试遍历每个块的内容时,partition会引发以下错误:each

helpers.js

"Assertion failed: The value that #each loops over must be an Array. You passed [object Object]"

template.hbs

Ember.Handlebars.registerHelper('partition', function(path, options){
  path = path === '' ? 'this' : path;
  var arr = [];
  var data = Ember.Handlebars.get(this, path, options).content;
  var ret = '';
  while(data.length){
    arr.push(data.splice(0, options.hash.size || 2));
  }
  for(var i = 0, len = arr.length; i < len; i++){
    ret = ret + options.fn(arr[i]);
  };
  return ret;
});
<h2>Your photos</h2> {{#partition controller.photos size=2}} <div class="slide"> {{#each this}} {{this.title}} {{/each}} </div> <br/><br/><br/> {{/partition}} 中的{p> this是正确大小的数组。

我怎样才能让它发挥作用? #partition从哪里获取内容?

要点可以在这里找到:https://gist.github.com/frekw/2d3627039b42891a0b0a

1 个答案:

答案 0 :(得分:3)

我解决了您的问题,请参阅this JSBin for a demo

  • 在帮助程序中,我创建了一个包含分区集合的新Ember.Object。此对象作为上下文传递给options.fn()

  • 我在块中添加了with帮助器来设置each块的上下文。

{{#partition photos size=2}}
  <div class="slide">
    {{#with collection}}
      {{#each}}
        {{title}}
      {{/each}}
    {{/with}}
  </div>
  <br/><br/><br/>
{{/partition}}

帮助者:

Ember.Handlebars.registerBoundHelper("partition", function(collection, options){

  var size = options.hash.size || 2;

  while(collection.length > 0)
  {
    var oc = Ember.Object.create({
      collection: collection.splice(0, size)
    });
    options.fn(oc);
  }

});

我希望这会有所帮助。