【问题标题】:Using Ember's Handlebars #each helper within a block helper that slices an array into chunks在将数组分割成块的块助手中使用 Ember 的 Handlebars #each 助手
【发布时间】:2023-03-21 09:09:01
【问题描述】:

我正在尝试将ArrayController 的content 切成块(用于演示目的)。在每个块中,我想迭代项目以正确渲染所有内容。

我尝试通过编写partition Handlebars 块助手来完成此操作,这似乎有效。但是,当我尝试遍历每个块的内容时,each 会抛出以下错误:"Assertion failed: The value that #each loops over must be an Array. You passed [object Object]"

helpers.js

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;
});

template.hbs

<h2>Your photos</h2>
{{#partition controller.photos size=2}}
  <div class="slide">
    {{#each this}}
      {{this.title}}
    {{/each}}
  </div>
  <br/><br/><br/>
{{/partition}}

#partition 中的this 是大小正确的数组。

我怎样才能让它工作? each 从哪里获取内容?

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

【问题讨论】:

    标签: javascript ember.js handlebars.js


    【解决方案1】:

    我解决了您的问题,请参阅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);
      }
    
    });
    

    我希望这会有所帮助。

    【讨论】:

    • 工作就像一个魅力,非常感谢!我仍然不完全确定为什么创建一个新的 Ember.Object 而不仅仅是迭代一个数组。我最好的猜测是它与#each 的实现细节有关。或者为什么#with 需要#each 才能工作。但我想我对 Ember 的理解会及时到达那里 :) 再次感谢!
    • 实际上,将我的原始解决方案包装在 #with 中似乎也可以。我想我需要阅读 Ember 的 Handlebars 助手中的范围。
    • @frekw 不客气。是的,Ember Handlebars 助手的文档记录非常糟糕。我也在想我应该能够传递一个数组。我希望他们在未来改进这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多