【问题标题】:Meteor: How do I successfully display data from two or more mongo collections on one view or page?Meteor:如何在一个视图或页面上成功显示来自两个或多个 mongo 集合的数据?
【发布时间】:2016-10-09 10:19:48
【问题描述】:

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

数据在日志中传递,因此发布和订阅工作正常,当我将我的助手从 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});
    }
  });
}

【问题讨论】:

    标签: mongodb templates meteor views


    【解决方案1】:

    你已经接近了。在home 模板中有两个{{#each articles}},但articles 没有home 的助手,因为你的助手是在内部模板上定义的。只需将您的 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 }} 循环,您通常需要考虑空列表的情况。

    【讨论】:

    • 是的!谢谢@MichelFloyd 解决了我的问题!
    猜你喜欢
    • 2013-06-14
    • 2016-09-27
    • 2012-01-01
    • 2017-05-03
    • 2019-09-11
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多