我有一个包含字段type
和number
的集合。
现在我用
打印集合中的文档{{#each myRows}}
<tr>
<td>{{type}}</td>
<td>{{number}}</td>
</tr>
{{/each}}
许多行具有相同的type
值,所以我想要&#39;分组&#39;行type
。我怎么能得到这个?我需要像
{{#types}}
<tr>
<th>{{type}}</th>
</tr>
{{#each numbersInType}}
<tr>
<td>{{type}}</th>
</tr>
{{/each}}
{{/each}}
答案 0 :(得分:2)
尝试这样的事情:
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);
}
});
助手的结果如下所示:
[ { type: 'a', numbers: [ 1, 2, 3 ] },
{ type: 'b', numbers: [ 10, 11, 12 ] },
{ type: 'c', numbers: [ 100 ] } ]
这是一个示例模板片段:
{{#each types}}
<tr>
<th>{{type}}</th>
</tr>
{{#each numbers}}
<tr>
<td>{{this}}</th>
</tr>
{{/each}}
{{/each}}