Search code examples
meteorspacebars

Meteor: Spacebars each parameter


I'm new to Meteor.js and have run into a problem.

I am passing in a user object to a profile template e.g.:

{
  _id: "D8JpXRQskm3grykjg",
  username: "foo",
  profile: {communities: ["AkGCakz6mSgMb8qyS", "j8aB3i5iscrC4ehkA"]},
}


<template name="profile">
  <h1> {{username}}: {{_id}} </h1>
  <h3>Communities</h3>
  <hr>
  {{#each profile.communities}}
    {{> communityItem}}
  {{/each}}
</template>

The problem is I've already written a communityItem template that I am using elsewhere which accepts the communityName. Is there a way that I can write a helper function, passing in the communityIds list that would return a list of community names? I would like:

...
{{#each getCommunityNames(profile.communities)}}
  {{> communityItem}}
{{/each}}
...

I could very well be approaching the problem the wrong way or not writing in a "Spacebars" fashion. Thanks!


Solution

  • sure you can:

    Template.myTemplate.helpers({
      getCommunityNames: function(commIds) {
        var communities = Communities.find({_id: {$in: commIds}}).fetch();
        return _.pluck(communities, 'name'); // returns ['Name 1', 'Name 2'];
      }
    });
    

    Note, the syntax method param not method(param)

    {{#each getCommunityNames profile.communities}}
      {{>communityItem}}
    {{/each}}