Jeff Levensailor
Jeff Levensailor

Reputation: 29

Meteor spacebars nested {{each}} helper issue

I have 2 collections: TestPlans and Users TestPlans has an array called "assigned" which contains user _ids. Users has an avatarUrl string

I need to iterate over each testPlan and furthermore each assignedUser and grab an avatarUrl for that user:

Something like {{#each testPlan}} {{#each assignedUser}} {{avatarUrl}}

the helper for testPlans I have:

testPlan: function() {
  var testPlans = TestPlans.find({}, { sort: {createdAt: -1}}).fetch();
  return testPlans;
}

the helper for assignedUser I have:

assignedUser: function(){
 var assignedUsers = TestPlans.findOne({_id: this._id}).assigned;
 return assignedUsers;
}

I'm not sure how call the avatarUrl for each assignedUser though. The query would be

Users.findOne({_id: thisUserId}).profile.avatarUrl;

Just not sure how to pass the userid exactly.

Upvotes: 0

Views: 176

Answers (2)

mutdmour
mutdmour

Reputation: 543

if assignedUsers is an array of userIds, which might be the best implementation in this case..

//html
{{#each testPlan}} 
   {{#each assignedUser}}
     {{profile.avatarUrl}}
     //you can do this because {{this}} is the user object
     //{{profile.avatarUrl}} is the same as {{this.profile.avatarUrl}}
   {{/each}}
{{/each}}

//js
assignedUser: function(){
   var assignedUsers = TestPlans.findOne({_id: this._id}).assigned;
   var usersCursor = Users.find({_id:{$in:assignedUsers}}});
   return usersCursor;
}

Upvotes: 0

jordanwillis
jordanwillis

Reputation: 10705

I would change your assignedUser template helper to accept a user ID parameter and then return the Avatar URL

assignedUser: function(userId) {
  return Users.findOne({_id: userId}).profile.avatarUrl
};

Then your template code would look something like this.

{{#each tp in testPlan}}
  {{#each au in tp.assignedUser}} 
    {{avatarUrl au._id}}
  {{/each}}
{{/each}}

Also, I like to use each...in instead of just each because it makes it more explicit what is actually happening

Upvotes: 0

Related Questions