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));
So, the template would be:
However, this template expects a two-dimensional array, so you would have to transform your data-object first.
Live demo: http://jsfiddle.net/emfKH/3/