繁体   English   中英

流星模板遍历数组

[英]Meteor template iterate through array

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等...]。

知道我做错了什么吗?

这是一个工作版本:

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 ,它在创建模板时异步设置,但在帮助器中同步读取。 如果您不熟悉这些技术,请参阅我关于范围反应性的文章。

  • each需要在<tr>

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

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

{{#each fixtures}}
  {{> fixture this}}
{{/each}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM