0

我正在尝试在 Meteor 空格键模板中显示一些关系数据。具体来说,我有两个系列,位置和天气。它们看起来像这样:

Location {
  _id: 'full-name',
  title: 'Full name',
  lat: '123.456',
  long: '123.456',
  order: 1
}

Weather {
  locName: 'full-name', // this name always matches a location _id
  temperature: '41.3'
}

我想在一个页面上显示来自这两个集合的信息。这样我就可以显示每个位置的最新天气(每页有 4-20 个)。为此,我在服务器端发布了两个集合的 Mongo 请求,如下所示:

Meteor.publish('allLocations', function() {
    return [
        Locations.find({}, { sort: { order: 1 } }),
        Weather.find({}) // The weather 
    ]    
});

然后我在我的路由器(铁路由器)中订阅了这个出版物:

Router.map(function() {
    this.route('locations', {
        waitOn: function () {
            return Meteor.subscribe('allLocations');
        }
    }
});

但是,当我进入我的空格键模板时,我被卡住了。我无法弄清楚在空格键中切换集合焦点的语法。

这是我要解析的模板的伪代码,但我知道这目前不起作用。

<template name="locations">
  <div class="locations-grid">
    {{#each locations}}
      <div class="location {{_id}}">
        This is the location template
        <h1>{{title}}</h1>
        {{#each weather}}
          <!-- Trying to pass the _id along to the weather template for filtering -->
          {{> weather _id}}
        {{/each}}
      </div>
      {{/each}}
    </div>
</template>

<template name="weather">
  This is the weather template
  {{#with weather}}
    <!-- Ideally, we've now switched contexts to the weather collection -->
    <h2>Temperature: <div class="temp">{{temperature}}</div></h2>
  {{/with}}
</template>

所以我的问题是,我在哪里告诉空格键将上下文切换到天气集合?如何将 _id 变量传递给天气模板,以便从集合中选择正确的数据?我知道我在这里错过了一大步,我只是不知道要检查流星空间的哪个部分。我知道我可能需要为天气模板指定订阅,但我不确定在哪里做,因为它不是真正的路线,因为它没有自己的页面。它只是作为位置模板中的子模板存在。

感谢您提供有关重组的任何提示或可能的建议。

4

1 回答 1

1

在我们开始之前,请阅读Meteor 模板和数据上下文指南- 它将正确地引导您了解#each块内的上下文。

您的目标是将正确的weather文档加入到相应的location文档中。这很容易通过为这两种类型引入子模板来实现。让我们从顶级模板开始:

<template name="locations">
  <div class="locations-grid">
    {{#each locations}}
      {{> location}}
    {{/each}}
  </div>
</template>

其中有一个locations这样的助手:

Template.locations.helpers({
  locations: function() {
    return Locations.find();
  }
});

接下来是location模板:

<template name="location">
  <div class="location">
    <h1>{{title}}</h1>
    {{#each weathers}}
      {{> weather}}
    {{/each}}
  </div>
</template>

其中有一个weather这样的助手:

Template.location.helpers({
  weathers: function() {
    return Weather.find({locName: this._id});
  }
});

这里的关键见解是location模板的上下文是单个位置文档,因此weather将仅返回位置实例的天气文档。最后,您的天气模板可能如下所示:

<template name="weather">
  <h2>Temperature: {{temperature}}</h2>
</template>

请注意,我们现在处于weather上下文中,因此#with不再需要 。

旁注 - 在您的发布者中使用排序在这种情况下没有影响

于 2014-10-26T17:51:51.143 回答