Reputation: 2524
I want to print a 2 dimensional grid based on the x (row) and y (column) ,which obtained from the collection.
I would like to do something like this:
{{for i=0; i<=x; i++}}
<ul class="row-{{i}}">
{{for c==; c <=y; y++}}
<li><span class="col-{{y}}">{{num}}</span></li>
{{num++}}
{{/for}}
</ul>
{{/for}}
The problem the meteor spacebars template doesn't support For loop as well as variables on the template. The iteration has to be done with while and each loop.
So how I gonna write the template helper and use it in the template?
//example data
var grid = [
{
x:10,
y:20,
title:"first block"
.....
},
....
];
Template.grid.helpers({
grid : function(){
var x = grid[0].x;
var y = grid[0].y;
for (i = 1; i <= x; i++){
for(c = 1; c <= y; c++){
//I don't know how to continue.
}
}
}
});
I am new to meteor, and only have experience in PHP.
Upvotes: 2
Views: 3001
Reputation: 2524
Okay, finally I figured it out. Here are the codes:
//example data
var grid = [
{
x:10,
y:20,
title:"first block"
.....
},
....
];
Template.grid.helpers({
grid : function(){
var x = grid[0].x;
var y = grid[0].y;
var row = [];
var num = 1; // for the increment number
for (i = 1; i <= x; i++){
row[i] = [];//let every row has it own array
for(c = 1; c <= y; c++){
row[i].push(num);//add the increment number into each row
num++;
}
}
return row;
}
});
And in the html template:
{{#each row in grid}}
<ul class="row-{{@index}}">
{{#each num in row}}
<li><span class="col-{{num}}">{{num}}</span></li>
{{/each}}
</ul>
{{/each}}
Note that the @index is for getting the array index. And it is only works in meteor >= 1.2 version.
Upvotes: 2
Reputation: 2010
With spacebars you can use the {{#each}}
tag. Here is an example for your case:
{{#each rows}}
<ul class="row-{{rowIndex}}">
{{#each columns}}
<li><span class="col-{{columnIndex}}">{{num}}</span></li>
{{/each}}
</ul>
{{/each}}
Your data would need to look like this in JSON:
{
rows: [
{
rowIndex: 1,
columns: [
{
columnIndex: 1,
num: 100,
},
{
columnIndex: 2,
num: 200,
},
]
},
{
rowIndex: 2,
columns: [
{
columnIndex: 1,
num: 100,
},
{
columnIndex: 2,
num: 200,
},
]
}
]
}
You can see that the JSON object has a rows
field which is an array. Each row
has a rowIndex
and an array of columns
. Each column
has a columnIndex
, etc.
You would need to name a helper like this and return that JSON object:
Template.grid.helpers({
rows: function() {
return theJSONObject.rows;
}
});
Upvotes: 1