Search code examples
if-statementmeteorhandlebars.jsroles

Meteor: Display text only if roles == 'webmaster'


I want to display information based on a user being iterated on a page.

I have the following template:

<template name="allUsers">
  <div>
    {{#each user}}
      {{username}}<br/>
      <!-- This is where I need some guidance -->
      {{#if roles == 'webmaster}} <!-- What's the correct way to do this? -->
        This user is a webmaster
      {{/if}}
    {{/each}}
  </div>
</template>

I'm using the alanning:roles package and in the server I have been sure to publish the roles field for users. roles.[0] will return webmaster for now and roles.[1] returns admin... But I know further down the line with adding roles it won't have the standard key of 0 = webmaster and 1 = admin.

Is there a way to just test IF the roles array contains 'webmaster' to be displayed on the client?


Solution

  • Here's a global template helper to help out with this.

    Template.registerHelper( 'isUserInRole', function( userId, role ) {
        return Roles.userIsInRole(userId, role);
    });
    
    <template name="allUsers">
      <div>
        {{#each user}}
          {{username}}
          {{#if isUserInRole _id 'webmaster'}}
            This user is a webmaster
          {{/if}}
        {{/each}}
      </div>
    </template>
    

    **Edited based on the first comment.