Easy way to create a grid using Handlebars.js?

I am trying to create a grid of five elements from objects in this array:

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

An array can contain from 1 to 50 objects, and the data format is the 1st array, coming from the Spine.js model. To separate the data and the presentation, I hope to save the data in the 1st array and use the presentation template (rudder templates) to start a new line on every fifth element, for example:

 <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 entire string to a helper function. Only my template looks like this:

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

It seems to win the use of templates. Is there an easy way to create a grid, as shown above, where the code is mainly in the template?

[Change] Solution

Change 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)); 
+8
javascript templates
source share
2 answers

So the template will 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 will first have to convert your data object.

 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/

+7
source share

try using an example tag table:

 <table> <thead> <th>head 1</th> <th>head 2</th> <th>head 3</th> </thead> <tbody> <tr> <td>column 1</td> <td>column 2</td> <td>column 3</td> </tr> </tbody> </table> 

and you can also provide identifiers and classes as their attributes for simple manipulation strategies.

0
source share

All Articles