How to use model data in template?

79 views Asked by At

I have created FIXTURES using ember-model and I am trying to access it on template, but it is not showing any result if I use {{model.name}}. It is working fine with each helper.

I want to access single node of model like {{model.name}} without using any each helper.

My model code:

Astcart.Home.FIXTURES=[
    {
        "id": "1",
        "logo_url": "img/logo.jpg",
        "name": "gau",
        "list": [
            {
                "id": "1",
                "name": "amit"
            },
            {
                "id": "2",
                "name": "amit1"
            }
        ]
    }
];

My router code :

  Astcart.HomeRoute = Ember.Route.extend({
    model: function() {
      return Astcart.Home.find();
    }
  });  

My template :

<script type="text/x-handlebars" data-template-name="home"> 

    {{model.name}}

    <ul>
        {{#each item in model}}                                         
            <img  {{bindAttr src="item.logo_url"}}></img>               
            <li>{{item.name}}</li>
            {{#each item in item.list}} 
                <li>{{item.name}}</li>
            {{/each}}               
        {{/each}}
    </ul>
</script>

I have updated my code here

1

There are 1 answers

2
Marcio Junior On BEST ANSWER

First, you need to change your template name to index, or your route to Astcart.ApplicationRoute, because the template name and route name must match.

The current configuration:

Route

Astcart.IndexRoute

Template

<script type="text/x-handlebars" data-template-name="application">

don't work.

The find() without params, will perform a find all data, and this will always return an array.

If you want a single data, you can do one of the following choices:

1- Pass the id in the find method, but you need to know the id:

Astcart.Home.find(1);

This will return a single object, then you can use {{model.name}} or {{name}} (because the context of the template is the model), without the each view helper.

2- Get the first object of the array:

{{#with model.firstObject as item}}
    <img  {{bindAttr src="item.logo_url"}}></img>               
    {{item.name}}
{{/with}}

I hope it helps