Search code examples
javascriptmeteormeteor-blazemeteor-helper

Meteor - display collection with conditions


I have a user based Meteor application with a collection representing groups.

A group is something like this:

{ name: groupname, members: [memberuseridlist], owner: owneruserid}

I have a template for these groups that looks like this:

{{#each groups}}
    <li>{{name}}
        -
        <button class="join">+</button>
        <button class="leave">-</button>
        <button class="delete">x</button>
    </li>
{{/each}}  

But I'd like to ensure that only the relevant buttons are displayed e.g.:

 {{#each groups}}
    <li>{{name}}
        -
        {{#unless ismember}}<button class="join">+</button>{{/unless}}
        {{#if ismember}}<button class="leave">-</button>{{/if}}
        {{#if isowner}}<button class="delete">x</button>{{/if}}
    </li>
{{/each}}  

I have a set of template helper methods but I don't understand how to pass the actual group into the function, so that I can evaluate ismember and isowner for each group.


Solution

  • The context within {{#each groups}} is a group document. So within your helpers you can use this to mean a group. Try something like this:

    Template.myTemplate.helpers({
      ismember: function() {
        return _.contains(this.memberuseridlist, Meteor.userId());
      },
      isowner: function() {
        return this.owner === Meteor.userId();
      }
    });
    

    If you wish to make these helpers more portable between your templates, see my article on models.