简体   繁体   English

流星:遍历用户角色以显示复选框

[英]Meteor: Iterate over user roles for displaying checkboxes

With this template I'm showing all results, which are stored in the users-collection: 使用此模板,我将显示所有结果,这些结果存储在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". 定义了一些角色,例如“ 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. 1)如果一个用户仅具有“ admin”角色,则只会显示一个复选框。 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'. 2)显示的角色描述应该为“更细”。 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). 现在,我考虑遍历roles所有元素,并检查roles是否存在(=选中)或不存在(=未选中)。 The values of the elements are for displaying the Label of the checkbox. 元素的值用于显示复选框的标签。

1) Would this be the correct way doing that? 1)这是正确的方法吗?

2) How do I connect the helper var roles to the template for checking? 2)如何将助手var roles连接到模板进行检查?

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: 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: 的HTML:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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