Meteor 模板助手和对集合字段的访问

Meteor Templates helpers and access to collections' fields

我有两个合集:

Group = {
  users: [Array_of_User]
}

User = {
  name: _string_
}

我正在列出组,我想在模板中了解用户是否在组中:

mytemplate.js

Template.mytemplate.helpers({
  groups: function(){
      return Groups.find();
  },
  currentUsername: 'test'
});

mytemplate.html

<template name="main">
  <ul>
    {{#each groups}}
    <li>
      {{#if [the group contains currentUsername] }}
      contains
      {{else}}
      doesn't contain
      {{/if}}
    </li>
    {{/each}}
  </ul>
</template>

问题是:我可以在助手身上放什么而不是 [the group contains currentUsername] 来让它工作?

此外,我并不是说这是实现它的方法。我愿意接受任何建议,即使这意味着我必须做出很多改变。

在您的每个块中,您的数据上下文成为正在迭代的当前组。因此,您可以编写一个引用当前数据上下文的辅助方法,如下所示:

userInGroup: function(username) {
  var userInGroup;
  this.forEach(function(groupUsername) {
    if (username == groupUsername) {
      userInGroup = true;
    }
  };
  return userInGroup;
}

'this' 在 userInGroup 模板助手中引用当前组,只要您在组迭代中使用该助手即可。

然后您可以像这样使用助手:

<template name="main">
  <ul>
    {{#each groups}}
    <li>
      {{#if userInGroup currentUsername}}
      contains
      {{else}}
      doesn't contain
      {{/if}}
    </li>
    {{/each}}
  </ul>
</template>

您可以使用 Underscore.js function _.findWhere(list, properties) 检查组是否包含用户名:

if (Meteor.isClient) {
    Template.main.helpers({
        groups: function() {
            return Groups.find();
        },
        currentUsername: 'Matthias',
        isInGroup: function(username) {
            return !!_.findWhere(this.users, {
                name: username
            });
        }
    });
}

<template name="main">
  <ul>
    {{#each groups}}
    <li>
      {{#if isInGroup currentUsername}}
        contains
      {{else}}
        doesn't contain
      {{/if}}
    </li>
    {{/each}}
  </ul>
</template>

if (Meteor.isServer) {
    Meteor.startup(function() {
        Groups.insert({
            users: [{
                name: "Matthias"
            }, {
                name: "Angie"
            }]
        });
    });
}

这里是MeteorPad.