![](/img/trans.png)
[英]Blaze template helper only returning on in a Spacebars each loop in Meteor/Mongo
[英]pass current value of spacebars:this as argument to new helper in meteor/blaze
我在Mongo集合中找到年份的独特实例,并将它们作为列表项传递到我的模板中。 在这些下面,我想要具有给定年份中月份的唯一出现次数的子列表,但是我不知道如何将年份传递给我的month()助手,以便我可以限制查询。
HTML是...
<template name="list">
<ul>
{{#each year}}
<li>
<h2>{{this}}</h2>
</li>
<ul>
{{#each month}}
<li>
<h3>{{this}}</h3>
</li>
{{/each}}
</ul>
{{/each}}
</ul>
</template>
JS是...
let monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
let findYears = function(){
var distinctYears = _.uniq(Events.find({}, {
sort: {start: 1}, fields: {start: true}
}).fetch().map(function(x) {
var d = new Date(x.start);
return d.getFullYear();
}), true);
return distinctYears;
};
let findMonths = function(){
var distinctMonths = _.uniq(Events.find({}, {
sort: {start: 1}, fields: {start: true}
}).fetch().map(function(x) {
var d = new Date(x.start);
return monthNames[d.getMonth()];
}), true);
return distinctMonths;
};
Template.list.onCreated( () => {
let template = Template.instance();
template.subscribe( 'events' );
});
Template.list.helpers({
year() {
foundYears = findYears();
return foundYears;
},
month() {
foundMonthNames = findMonths();
return foundMonthNames;
}
});
我希望能够将year()帮助程序当前打开的年份作为我month()帮助程序的参数,以便我可以编辑findMonths函数以将其查询限制为仅该年内发生的事件,但是我不知道该怎么做,也不知道如何从客户端查询MongoDB仅一个月(我的所有活动日期均为ISODate格式)。
我希望我的问题很清楚。 抱歉,我知道我可能使用了不正确的术语。
如果我理解正确,那么您会遇到两个问题-将year
传递到您的month
帮助器中,以及使用该参数使查询更具体-是吗?
要将year
传递给帮助者,请遵循{{#each thing in things}}
约定( 在此处进行说明)更改代码。 因此,您的模板代码将变为:
<template name="list">
<ul>
{{#each year in getYears}}
<li>
<h2>{{year}}</h2>
</li>
<ul>
{{#each month in (getMonths year)}}
<li>
<h3>{{month}}</h3>
</li>
{{/each}}
</ul>
{{/each}}
</ul>
</template>
然后,您的year
助手将保持不变(除非我更改了名称以使其更清晰!),而您的month
助手将仅接受以下参数:
Template.list.helpers({
getYears() {
foundYears = findYears();
return foundYears;
},
getMonths(year) {
foundMonthNames = findMonths(year);
return foundMonthNames;
}
});
最后,您的findMonths
函数。 可能有不同/更简便的方法,但是您可以通过比较早晚的日期(例如,大于上一年的12月31日而小于下一年的1月1日)来获得年份:
let findMonths = function(year){
var query = {
start: {
$gt: new Date(year - 1, 11, 31),
$lt: new Date(year + 1, 0, 1)
}
}
var distinctMonths = _.uniq(Events.find(query, {
sort: {start: 1}, fields: {start: true}
}).fetch().map(function(x) {
var d = new Date(x.start);
return monthNames[d.getMonth()];
}), true);
return distinctMonths;
};
(如果您希望将其添加到午夜之前,则可以添加小时,分钟和毫秒)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.