user3848987
user3848987

Reputation: 1657

Meteor: Iterate over user roles for displaying checkboxes

With this template I'm showing all results, which are stored in the users-collection:

<template name="user">
    {{#each users.roles}}
        <input type="checkbox" data-role="{{this}}">{{this}}
    {{/each}}
</template>

There are some roles defined like "admin", "editor", "user_manage". But this leads to some problems:

1) If one user has just the role "admin", there will only one checkbox displayed. But I need to display all possible roles. Only if the role is in the profile, the checkbox should be checked.

2) The displayed description of the role should be 'nicer'. I mean the result should be like:

<input type="checkbox" data-role="admin"> Administrator
<input type="checkbox" data-role="editor"> Editor
<input type="checkbox" data-role="user_manage"> Manage users

I guess I need a helper:

Template.user.helpers({
    var roles = {admin: 'Administrator', editor: 'Editor', user_manage: 'Manage users'};
    return roles;
});

Now I think of iterating over all elements in roles and checking if the role exists (=checked) or not (=unchecked). The values of the elements are for displaying the Label of the checkbox.

1) Would this be the correct way doing that?

2) How do I connect the helper var roles to the template for checking?

Upvotes: 0

Views: 214

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20246

You're basically on the right track! Your helper needs to return an array of objects instead of an object. Then you need a helper which returns a boolean based on the whether that role is in the user's role array. For example:

js:

Template.user.helpers({
  roles: function(){
    return [
      { label: 'admin', name: 'Administrator'},
      { label: 'editor', name: 'Editor'},
      { label: 'user_manage', name: 'Manage users'}
    ];
  },
  hasRole: function(role){
    return Meteor.user().roles.indexOf(role)>-1; //assuming user.roles is just an array
  }
});

html:

<template name="user">
  {{#each roles}}
    <input type="checkbox" data-role="{{this.label}}"
    {{#if hasRole this.label}}checked{{/if}}>{{this.name}}
  {{/each}}
</template>

Upvotes: 0

Related Questions