Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to create a grid with Handlebars.js?

I'm attempting to generate a grid of divs five elements wide from the objects in this array:

[{n:'a'},{n:'b'},{n:'c'},{n:'d'}...{n:'y'}];

The array may contain between 1 and 50 objects, and the data format is a 1d array coming from a Spine.js model. In order to separate data and presentation, I'm hoping to keep the data in a 1d array, and use the view (handlebars template) code to start a new row on every 5th item, like so:

<div class="grid">
  <div class="row">
    <div class="cell"> a </div>
    <div class="cell"> b </div>
    <div class="cell"> c </div>
    <div class="cell"> d </div>
    <div class="cell"> e </div>
  </div>
  <div class="row">
    <div class="cell"> f </div>
    etc...
</div>

I have a solution working by returning the whole string in a helper function. Only my template looks like:

<script id="grid-template" type="text/x-handlebars-template">
  {{#grid}}
  {{/grid}}
</script>

That seems like it defeats the point of using templates. Is there a simple way to create a grid like the above, where the code resides mostly in the template?

[Edit] Solution

Modify the data in the controller, based on @Sime's answer below.

Template code:

<script id="grid-template" type="text/x-handlebars-template">
  {{#rows}}
    <div class="row">
      {{#cells}}
        <div class="cell">
          {{n}}
        </div>
      {{/cells}}
    </div>
  {{/rows}}
</script>

Controller rendering code ():

  this.data=[{n:'a'},{n:'b'},{n:'c'},{n:'d'}...{n:'y'}]; // previously set
  this.rows=[];
  var step=5,
  i=0,
  L=this.data.length;
  for(; i<L ; i+=step){
    this.rows.push({cells:this.data.slice(i,i+step)});
  };

  this.el.html(this.template(this));
like image 935
Adam Avatar asked Feb 14 '12 01:02

Adam


1 Answers

So, the template would be:

<script id="template" type="x-handlebars-template">
    <div class="grid">
        {{#each this}}
        <div class="row">
            {{#each this}}
            <div class="cell">{{n}}</div>
            {{/each}}
        </div>
        {{/each}}
    </div>
</script>

However, this template expects a two-dimensional array, so you would have to transform your data-object first.

function transform ( arr ) {
    var result = [], temp = [];
    arr.forEach( function ( elem, i ) {
        if ( i > 0 && i % 5 === 0 ) {
            result.push( temp );
            temp = [];
        }
        temp.push( elem );
    });
    if ( temp.length > 0 ) {
        result.push( temp );
    }
    return result;
}

Live demo: http://jsfiddle.net/emfKH/3/

like image 65
Šime Vidas Avatar answered Sep 19 '22 11:09

Šime Vidas