emadalam / atvjs

Blazing fast Apple TV application development using pure JavaScript
https://emadalam.github.io/atvjs
MIT License
311 stars 49 forks source link

Fetching data and display it #11

Closed procom closed 8 years ago

procom commented 8 years ago

Hello,

I would like to fetch json and display it on template.

I use :

ATV.Page.create({
    name: 'home',
    url: 'http://www.example.com/data.json',
    template: template
});

data.json :

{
    "CATALOG": {
        "ITEM": [{
            "TITLE": "Title 1"
        }, {
            "TITLE": "Title 2"
        }, {
            "TITLE": "Title 3"
        }]
    }
}

in template.hbs, I use :

... <title>{{ CATALOG.ITEM[0].TITLE }}</title> ...

But I have error launching application. How do I do to get the first title ?

emadalam commented 8 years ago

Can you please be more specific about the error that you receive, seems like some issue with your application initialisation. Attaching a sample app for your reference, do the following after extracting the project, then run the attached xcode project. Kindly close the issue if things are working as expected.

$ cd client
$ npm install
$ gulp

appletv-sample-app-using-atvjs.zip

procom commented 8 years ago

Hello,

Your sample works.

But if your json is :

[{
    "title": "Title 1",
    "description": "Description 1"
}, {
    "title": "Title 2",
    "description": "Description 2"
}]

How to get "Title 2" in the template.hbs With :

... <title>{{ title[1] }}</title> ...

it does not work

emadalam commented 8 years ago

@procom You need to read the docs about Handlebars templates. It is a logic less template engine and doesn't encourage putting logic inside your templates.

Having said that you can use handlebars' each helper to iterate through your json data. Or a better approach would be to transform the data before passing it on to the template. atvjs provides the data tranformation function for such use cases.

ATV.Page.create({
    name: 'home',
    url: 'http://www.example.com/data.json',
    template: template,
    // data method will be called after fetching the json data
    // and before applying the data to the provided template
    data: function(response) {
        // the response object will contain your entire json data fetched from the url
        // you can select the required values and return the final data object
        return {
            title: response[1].title
        };
    }
});

you would then be able to use the same in the handlebars template

... <title>{{ title }}</title> ...
procom commented 8 years ago

Thank you