如何显示"发布 - 复合集合"在模板视图上

时间:2017-05-26 14:03:26

标签: meteor meteor-blaze

考虑https://github.com/englue/meteor-publish-composite

给出的例子

如何在模板视图中显示嵌套子项。我的意思是,在视图上的帖子 上显示 前2条评论。

我在互联网上搜索了很多关于模板视图中这个子树显示的内容,但没有找到。

代码

publishComposite('topTenPosts', {
    find() {
        // Find top ten highest scoring posts
        return Posts.find({}, { sort: { score: -1 }, limit: 10 });
    },
    children: [
        {
            find(post) {
                // Find post author. Even though we only want to return
                // one record here, we use "find" instead of "findOne"
                // since this function should return a cursor.
                return Meteor.users.find(
                    { _id: post.authorId },
                    { fields: { profile: 1 } });
            }
        },
        {
            find(post) {
                // Find top two comments on post
                return Comments.find(
                    { postId: post._id },
                    { sort: { score: -1 }, limit: 2 });
            },
            children: [
                {
                    find(comment, post) {
                        // Find user that authored comment.
                        return Meteor.users.find(
                            { _id: comment.authorId },
                            { fields: { profile: 1 } });
                    }
                }
            ]
        }
    ]
});

1 个答案:

答案 0 :(得分:0)

使用Blaze它应该只是一组简单的模板,您可以在帮助器中搜索相关的注释和作者,使用嵌套的{{#each}}循环显示帖子和注释。

HTML:

<template name="posts">
{{#each posts}}
  Title: {{title}} posted on: {{date}} by: {{authorName}}
  {{#each comments}}
    {{> comment}}
  {{/each}}
{{/each}}
</template>

<template name="comment">
Post comment {{body}} by {{authorName}} on {{createdAt}}
</template>

现在为帮手:

Template.posts.helpers({
  posts(){
    return Posts.find({}, { sort: { score: -1 }, limit: 10 });
  },
  comments(){
    return Comments.find({ postId: this._id },{ sort: { score: -1 }, limit: 2 });
  },
  authorName(){
    return Meteor.users.findOne(this.authorId).username;
});

Template.comment.helpers({
  authorName(){
    return Meteor.users.findOne(this.authorId).username;
  },
});

请注意在这些助手中使用thisthis将是评估点的数据 context 的值。 {{#each}}this内部采用当前文档的值,即带键的对象。

如果您愿意,可以通过创建全球帮助来保持authorName助手干。