简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM