最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Display the first item in hasMany ember relationship in handlebars template - Stack Overflow

programmeradmin4浏览0评论

I need to display the first item in an hasMany relationship

Basically a thread could have more than 1 author but I need to display only the first one in a particular template

I've the following json

{
    threads: [
        {
           id: 1,
           authors: [2,3]
        }
    ],
    authors: [
        {
            id: 2,
            fullname: "foo"
        },
        {
            id: 3,
            fullname: "bar"
        }
    ]        
}

And the following models

App.Thread = DS.Model.extend({
    authors: DS.hasMany('author')
});

App.Author = DS.Model.extend({
    fullname: DS.attr('string')
});

now in my template I'm tring to do something like {{thread.authors[0].fullname}} but it doesn't work. I've tried also thread.authors.0.fullname according to the handlebars syntax but nothing changed.

Thnx in advance for your help

I need to display the first item in an hasMany relationship

Basically a thread could have more than 1 author but I need to display only the first one in a particular template

I've the following json

{
    threads: [
        {
           id: 1,
           authors: [2,3]
        }
    ],
    authors: [
        {
            id: 2,
            fullname: "foo"
        },
        {
            id: 3,
            fullname: "bar"
        }
    ]        
}

And the following models

App.Thread = DS.Model.extend({
    authors: DS.hasMany('author')
});

App.Author = DS.Model.extend({
    fullname: DS.attr('string')
});

now in my template I'm tring to do something like {{thread.authors[0].fullname}} but it doesn't work. I've tried also thread.authors.0.fullname according to the handlebars syntax but nothing changed.

Thnx in advance for your help

Share Improve this question asked Apr 1, 2014 at 19:31 Fed03Fed03 5855 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 18

Use Ember.Enumerable's firstObject:

{{thread.firstObject.fullName}}

If you are going to use it in a lot of places, its best to define it as a puted property in the model:

App.Thread = DS.Model.extend({
  authors: DS.hasMany('author')

  firstAuthor: Ember.puted.alias('authors.firstObject')
});

and use it in your templates as:

{{firstAuthor.name}}
发布评论

评论列表(0)

  1. 暂无评论