Search code examples
ember.jshandlebars.js

Multiple ul with single array in ember handlebars template


Lets say I've an array with 6 items and I want print them 3 per list

Ex

//arr = [1,2,3,4,5,6];
//html
<div class="first">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>

<div class="second">
  <ul>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>

How can I accomplish that with ember/handlebars? Thanks


Solution

  • I ended doing this:

    in template.hbs

    {{#each set in arraySets}}
      <div class="col-sm-6">
        <ul class="list-unstyled">
          {{#each item in set }}
            <li>{{item.name}}</li>
          {{/each}}
        </ul>
      </div>
    {{/each}}
    

    in the related controller

    import Ember from "ember";
    import Collection from "../../utils/collection";
    
    export default Ember.ObjectController.extend({
    
        // ....
    
        arraySets: function() {
            var infos = this.get('model.infos');
            return Collection.create({ content: infos }).divide();
        }.property()
    });
    

    and who does the hard work is the utils/collection.js

    import Ember from "ember";
    
    var Collection = Ember.ArrayProxy.extend({
        divide: function (size = 2) {
            var array = this.get('content');
            var length = array.length;
            var limit = Math.ceil(length / size);
            var sets = Ember.A([]);
    
            for (var i = 0; i < Math.min(size, length); i++) {
                sets.pushObject(array.slice(i * limit, (i + 1) * limit));
            }
    
            return Collection.create({content: sets});
        }
    });
    
    export default Collection;
    

    I hope that this could help someone else!