簡體   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