Reputation: 41
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>
I am getting a list of fixtures of a football team and returning it as an array 'fixtures'. I could not get my template to list the fixtures. In the console 'resuls.data.fixtures' returns [obj,obj,obj, obj etc...].
Any idea what I am doing wrong?
Upvotes: 3
Views: 4272
Reputation: 64312
Here is a working version:
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 [];
}
}
});
}
<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>
The fixtures
array was not being parsed out of the original HTTP result, so you were passing extra data (like the headers) back to the client.
Helpers should be synchronous. Here we use a ReactiveVar which is asynchronously set when the template is created, but synchronously read in the helper. See my article on scoped reactivity if these techniques are unfamiliar to you.
The each
needs to be outside of the <tr>
.
Make sure to run: $ meteor add reactive-var http
for the above example to work.
Upvotes: 3
Reputation: 2192
Try passing the object returned from your each loop, which should be this
, to your fixture template:
{{#each fixtures}}
{{> fixture this}}
{{/each}}
Upvotes: 2