I have a collection with fields type
and number
.
Right now I'm printing docs in the collection with
{{#each myRows}}
<tr>
<td>{{type}}</td>
<td>{{number}}</td>
</tr>
{{/each}}
Many rows has the same type
value so I want to 'group' rows by type
. How can I obtain this? I need something like
{{#types}}
<tr>
<th>{{type}}</th>
</tr>
{{#each numbersInType}}
<tr>
<td>{{type}}</th>
</tr>
{{/each}}
{{/each}}
Give something like this a try:
Template.myTemplate.helpers({
types: function() {
// fetch your rows somehow
var rows = Collection.find().fetch();
// hash of type data
var types = {};
_.each(rows, function(row) {
var type = row.type
// initialize each type in the hash if it isn't defined
if (types[type] == null)
types[type] = {type: type, numbers: []};
// add the numbers to the array for this type
types[type].numbers.push(row.number);
});
// the values of the has contain an array of properly formed data
return _.values(types);
}
});
The result of the helper will look like this:
[ { type: 'a', numbers: [ 1, 2, 3 ] },
{ type: 'b', numbers: [ 10, 11, 12 ] },
{ type: 'c', numbers: [ 100 ] } ]
Here's a sample template fragment:
{{#each types}}
<tr>
<th>{{type}}</th>
</tr>
{{#each numbers}}
<tr>
<td>{{this}}</th>
</tr>
{{/each}}
{{/each}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.