Meteor:如何在一个视图或页面上成功显示来自两个或多个 mongo 集合的数据?

Meteor: How do I successfully display data from two or more mongo collections on one view or page?

我有两个 mongo 集合,分别名为 "theCollection" 和 "StreamingCollection",代表两类数据。我想在我的主页上显示来自不同集合的两组数据,在一个更大的模板 "Home" 中的两个相应模板 "red" 和 "blue" 中,如下所示。

数据正在日志中传递,因此发布和订阅工作正常,当我将助手从 template.red.helpers 更改为 template.Home.helpers 时,数据显示,但只有一个集合。

如何在一页上成功显示来自两个或多个集合的数据?

下面显示了我的主页,它只有一个模板 "Home",这个模板包含两个 #each 列表,用于不同的集合,红色和蓝色,它们本身就是模板。

<template name="Home">

<section>
    <div>
      <ul>
      {{#each articles}}
        {{> red}}
      {{/each}}
    </ul>
  </div>
     <div>
      <ul>
      {{#each articles}}
        {{> blue}}
      {{/each}}
    </ul>
  </div>

</section>

红蓝模板是这样的

<template name="red">
      <li>
    <div><img src="{{thumbnail}}"></div>
      <div>{{title}}</div>
  </li>
</template>

  <template name="blue">
     <li>
        <div><img src="{{thumbnail}}"></div>
          <div>{{title}}</div>
  </li>
</template>

这些是我的帮手

if (Meteor.isClient) {
  Template.red.helpers({
    articles: function () {
      return theCollection.find({}, {sort: {count:-1}, limit:1});
    }
  });

  Template.blue.helpers({
    articles: function () {
      return StreamingCollection.find({}, {sort: {count:-1}, limit:1});
    }
  });
}

你很接近。 home 模板中有两个 {{#each articles}},但是 home 没有 articles 助手,因为您的助手是在内部模板上定义的。只需将 html 更改为:

<template name="Home">
<section>
  <div>
    {{> red}}
  </div>
  <div>
    {{> blue}}
  </div>   
</section>
</template>

<template name="red">
<ul>
  {{#each articles}}
    <li>
      <div><img src="{{thumbnail}}"></div>
      <div>{{title}}</div>
    </li>
  {{/each}}
</ul>
</template>

<template name="blue">
<ul>
  {{#each articles}}
    <li>
      <div><img src="{{thumbnail}}"></div>
      <div>{{title}}</div>
    </li>
  {{/each}}
</ul>
</template>

html 在子模板中与主模板中的内容是品味和风格的问题。您应该考虑您的模板可在多个父模板中重复使用。对于 {{#each }} 循环,您通常要考虑空列表的情况。