Hugo
Hugo

Reputation: 155

How to pass json data to a meteor template

I'm trying to pass data from a json rest api to a meteor template

I get the JSON from a HTTP GET like this:

if (Meteor.is_client) {

    Meteor.http.call("GET", "https://public-api.wordpress.com/rest/v1/freshly-pressed", function (err, result){
        console.log(result.content);
    })
}

if (Meteor.is_server) {

}

and i can see the JSON data in the browser console

how can i pass the data to a template?

Upvotes: 1

Views: 1638

Answers (2)

Hubert OG
Hubert OG

Reputation: 19544

There are several ways, depending on where you make the call and what packages you use. The simplest one is to use session and a helper:

HTTP.get(..., function(err, result) {
  Session.set('httpResult', result);
});

Template.myTemplate.json = function() {
  return Session.get('httpResult');
};


<template name="myTemplate">
  {{json.property}}
  {{#with json}}
    {{property}}
    {{otherProperty}}
    {{lotsOfProperties}}
  {{/with}}
</template>

Upvotes: 3

Erez Hochman
Erez Hochman

Reputation: 1708

The simplest way would be to save the results in a variable and use a #with in your template.

 Meteor.http.call("GET", "https://public-api.wordpress.com/rest/v1/freshly-pressed", function (err, result){
    my_json = result.content;
})

template:

<template name="json_data">
   {{#with my_jason}}
      ...
   {{/with}}

Upvotes: 1

Related Questions