Jamille
Jamille

Reputation: 99

Meteor js condition with each loop

I am very new to meteor js and trying to build a small messaging app.

What I want to do is I want to check a condition within the loop with

Probably, something like this.

<div class="messages-box">
{{#each messages}}

    {{#if isCurrentUserCan}}
        <p>{{msg that user can do bla bla}}</p>
    {{else}}
        <p>{{msg that user can't do}}</p>
    {{/if}}

    </div>
{{/each}}
</div>

js

Template.body.helpers({
'isCurrentUserCan': function(){
  if ( random message box's user ID == Meteor.userId() ){
      return 'This user can do bla bla';
 }else{
      return 'This user can't do';
 }
}
});

How can I achieve it?

Upvotes: 0

Views: 239

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

You're iterating over a collection of messages. Let's say that each message includes a userId key. You can check to see if the userId of the message is the same as the current user and return true or false accordingly.

Template.body.helpers({
  'isCurrentUserCan'() {
    return this.userId === Meteor.userId();
  }
});

Inside the {{each}} this is set to the current message object so this.key directly accesses the corresponding key.

Upvotes: 3

Related Questions