Reputation: 1
I'm pretty much a beginner and I'm using Meteor for a quick prototype we are using for UX testing at work. (UX designer does coding, yay).
Now here is the problem, I have two collections with two templates: Comments
and Tasks
. I want to show a combined view of these two sorted by creation date. Right now I am only able to first show comments and after that show the tasks, with their respective templates simply by doing:
<template name="yourTemplate">
{{#if comments.count}}
{{#each comments}}
{{> comment}}
{{/each}}
{{else}}
<li class="empty">
<h1>No comments yet :(</h1>
{{#if currentUser}}
<p>Why don't you <span class="write-comment">write one?</span></p>
{{else}}
<p>Log in to write a new one.</p>
{{/if}}
</li>
{{/if}}
{{#each tasks}}
{{> task}}
{{/each}}
</template>
Is there a way to simply "unify" the view? I am doing everything locally on the client without any server-side things and no security, since it is all done locally on a test system with a moderator sitting next to the test subject, so I left it unsecure and autopublish on for a very quick prototype.
I guess a way would be to put the comments and the tasks into an array and sort it in there before displaying, but would that still be reactive and work?
I am also lost on the syntax for that I have to say.
Thanks in advance for any help.
Upvotes: 0
Views: 34
Reputation: 2677
As you mentioned, you can write a helper which combines both of them. Since it is a helper it will be reactive, if you query on collections (or any reactive data sources) in that helper.
Template.yourTemplate.helpers({
items: function () {
// get comments and tasks - Add appropriate query properties to filter results
var comments = Comments.find({}).fetch();
var tasks = Tasks.find({}).fetch();
//Add a property to each comment object to identify whether an item is a comment or task
comments = _.map(comments, function (obj) {
obj.isComment = true;
return obj;
});
//combine comments and tasks into single array
var items = comments.concat(tasks);
//sort combined array by creation date
items = _.sortBy(items, function (item) {
return item.creationDate; //edit this based on your requirement
});
return items;
}
});
Then in your template
<template name="yourTemplate">
{{#if items.count}}
{{#each items}}
<!-- This is the property that we have added in helper -->
{{#if this.isComment}}
{{> comment}}
{{else}}
{{> task}}
{{/if}}
{{/each}}
{{else}}
<li class="empty">
<h1>No comments and tasks yet :(</h1>
{{#if currentUser}}
<p>Why don't you <span class="write-comment">write a comment?</span></p>
{{else}}
<p>Log in to write a new comment.</p>
{{/if}}
</li>
{{/if}}
</template>
Hope it helps.
Upvotes: 1