【问题标题】:How to display children of "publish-composite collection" on Template View如何在模板视图上显示“发布复合集合”的子级
【发布时间】:2017-10-27 11:11:26
【问题描述】:

考虑https://github.com/englue/meteor-publish-composite给出的例子

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

我在互联网上搜索了很多在模板视图上显示的子树,但没有找到。

代码

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 } });
                    }
                }
            ]
        }
    ]
});

【问题讨论】:

  • 您的客户端数据库中没有实际的树。每个文档都进入其相应的集合。到目前为止,您尝试过什么,您在哪里卡住了?

标签: meteor meteor-blaze


【解决方案1】:

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

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;
  },
});

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

如果您愿意,可以通过创建一个全局帮助器来保持authorName 帮助器干燥。

【讨论】:

  • 你好吗?如果我们立即在模板中进行订阅和帮助程序,那么publish-composite 包需要什么?制作嵌套的孩子?我不明白其背后的目的。我的代码在没有publish-composite 包的情况下仍然可以工作,对吧,你上面的代码?
  • Publish-composite 可帮助您确保准确发布所需的内容,而不是更多。在此处发布嵌套数据的方法有多种。
猜你喜欢
  • 2018-09-16
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
相关资源
最近更新 更多