流星模板遍历数组

时间:2015-01-18 23:18:42

标签: javascript meteor meteor-helper

js

if (Meteor.isClient) {

  Template.body.helpers({
    fixtures: function () {
      Meteor.call("checkTwitter", function(error, results) {
        return results.data.fixtures;
      });
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
  Meteor.methods({
        checkTwitter: function () {
            this.unblock();
            var url = "http://api.football-data.org/alpha/teams/73/fixtures";
            return Meteor.http.call("GET", url);
        }
    });
}

HTML

<body>
  <h1>Tottenham Hotspur</h1>
  <button>Click Me</button>
  <table class="table">
    <th>
        <td>Date</td>
        <td>Home</td>
        <td>Result</td>
        <td>Away</td>
    </th>
    <tr>
        {{#each fixtures}}
        {{> fixture}}
      {{/each}}
    </tr>
  </table>
</body>

<template name="fixture">
    <td>{{date}}</td>
    <td>{{home}}</td>
    <td>{{result}}</td>
    <td>{{away}}</td>
</template>

我得到一个橄榄球队的固定装置列表并将其作为阵列'固定装置'返回。我无法让我的模板列出灯具。在控制台'resuls.data.fixtures'中返回[obj,obj,obj,obj等...]。

知道我做错了吗?

2 个答案:

答案 0 :(得分:3)

这是一个工作版本:

app.js

if (Meteor.isClient) {
  Template.matches.created = function() {
    this.matches = new ReactiveVar([]);

    var self = this;
    Meteor.call('getMatches', function(error, result) {
      if (result)
        self.matches.set(result);
    });
  };

  Template.matches.helpers({
    matches: function() {
      return Template.instance().matches.get();
    }
  });
}

if (Meteor.isServer) {
  Meteor.methods({
    getMatches: function() {
      var url = "http://api.football-data.org/alpha/teams/73/fixtures";
      try {
        var fixtures = HTTP.get(url).data.fixtures;
        return fixtures;
      } catch (e) {
        return [];
      }
    }
  });
}

app.html

<body>
  {{> matches}}
</body>

<template name="matches">
  <h1>Tottenham Hotspur</h1>
  <table class="table">
    <th>
      <td>Date</td>
      <td>Home</td>
      <td>Result</td>
      <td>Away</td>
    </th>
    {{#each matches}}
      <tr>
        {{> match}}
      </tr>
    {{/each}}
  </table>
</template>

<template name="match">
  <td>{{date}}</td>
  <td>{{homeTeamName}}</td>
  <td>{{result.goalsHomeTeam}}:{{result.goalsAwayTeam}}</td>
  <td>{{awayTeamName}}</td>
</template>

备注

  • fixtures数组未从原始HTTP结果中解析出来,因此您将额外数据(如标题)传递回客户端。

  • 助手应该是同步的。这里我们使用ReactiveVar,它在创建模板时异步设置,但在帮助器中同步读取。如果您不熟悉这些技术,请参阅scoped reactivity上的文章。

  • each必须在<tr>之外。

  • 请确保运行:$ meteor add reactive-var http以使上述示例正常工作。

答案 1 :(得分:2)

尝试将每个循环返回的对象(this)传递给 fixture 模板:

{{#each fixtures}}
  {{> fixture this}}
{{/each}}
相关问题