我正在尝试找到一种不错的流星风格方法来解决这个问题。
我有一组按日期排序的 Mongo 文档,可以轻松地显示在列表中:
<template name="logbook">
<h1>{{title}}</h1>
<div>
{{#each entries}}
{{> Entry}}
{{/each}}
</div>
</template>
现在,每次年份变化时,我都想输出它,这样我就会得到这样的东西:
2014
年文档 1
文档 2
2013
年文档 3
文档 4
文档 5
等。
这是流星,我希望列表是被动的。如果收到新文档,则应将其插入列表中的正确位置,并在必要时添加年份。
谁能提出一个明智的方法来解决这个问题?
您可以使用助手来检查年份是否与上一条记录相同,如果不是 - 他将输出它,例如
<template name="Entry">
{{year}}
{{data}}
</template>
在 js 中
year: function(){
//operations that will return year to some variable, for example year_variable
if(global_variable===undefined){
global_variable=year_variable;
return year_variable;
}
if(global_variable===year_variable) return false;
else return year_variable;
}
没有必要将其设为全局,您可以使用会话
这可能不是您在命名约定方面所寻找的,但它会让您了解我将如何处理这个问题:
- 创建唯一年份列表
- 每年,呈现一个模板(日志)
- 在每个日志中,循环访问该年的所有条目
这是一个完整的工作解决方案:
应用.html
<body>
{{#each years}}
{{> logbook}}
{{/each}}
</body>
<template name="logbook">
<h2>{{year}}</h2>
<ol>
{{#each entries}}
<li>{{text}}</li>
{{/each}}
</ol>
</template>
应用.js
if (Meteor.isClient) {
// create a client-side collection for testing
Entries = new Mongo.Collection(null);
Meteor.startup(function() {
// insert some data in the wrong order to test sorting
Entries.insert({text: 'doc6', date: new Date('1/3/2013')});
Entries.insert({text: 'doc4', date: new Date('1/1/2013')});
Entries.insert({text: 'doc5', date: new Date('1/2/2013')});
Entries.insert({text: 'doc3', date: new Date('1/3/2014')});
Entries.insert({text: 'doc1', date: new Date('1/1/2014')});
Entries.insert({text: 'doc2', date: new Date('1/2/2014')});
});
Template.body.helpers({
years: function() {
// return a list of unique sorted objects with a year field
return _.chain(Entries.find().fetch())
// pluck out the dates
.pluck('date')
// convert each date to a year
.map(function(date) {return date.getFullYear();})
// sort the years in reverse order
.sortBy(function(year) {return -year;})
// find only the unique values
.uniq(true)
// '2014' -> {year: '2014'}
.map(function(year) {return {year: year};})
.value();
}
});
Template.logbook.helpers({
entries: function() {
var year = this.year;
var entries = Entries.find({}, {sort: {date: 1}}).fetch();
// return a list of entries only for this year
return _.filter(entries, function(entry) {
return entry.date.getFullYear() === year;
});
}
});
}