我有两个系列:
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]
以使其有效?
另外,我并不是说这是做到这一点的方法。我对任何建议持开放态度,即使这意味着我必须改变很多。
答案 0 :(得分:2)
您可以使用Underscore.js函数_.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。
答案 1 :(得分:0)
在每个块中,您的数据上下文将成为正在迭代的当前组。因此,您可以编写一个引用当前数据上下文的辅助方法,如下所示:
userInGroup: function(username) {
var userInGroup;
this.forEach(function(groupUsername) {
if (username == groupUsername) {
userInGroup = true;
}
};
return userInGroup;
}
只要在组迭代中使用帮助程序,userInGroup模板中的'this'就会引用当前组。
然后您可以使用这样的帮助:
<template name="main">
<ul>
{{#each groups}}
<li>
{{#if userInGroup currentUsername}}
contains
{{else}}
doesn't contain
{{/if}}
</li>
{{/each}}
</ul>
</template>