在车把模板中显示具有许多余烬关系的第一项

Display the first item in hasMany ember relationship in handlebars template

本文关键字:关系 一项 多余 显示 许多余      更新时间:2023-09-26

我需要显示具有许多关系中的第一项

基本上一个线程可以有多个作者,但我只需要在特定模板中显示第一个作者

我有以下json

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

以及以下型号

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

现在在我的模板中,我想做一些类似{{thread.authors[0].fullname}}的事情,但它不起作用。我也尝试了根据车把语法thread.authors.0.fullname,但没有任何变化。

提前感谢您的帮助

使用 Ember.Enumerable 的firstObject

{{thread.firstObject.fullName}}

如果要在很多地方使用它,最好将其定义为模型中的计算属性:

App.Thread = DS.Model.extend({
  authors: DS.hasMany('author')
  firstAuthor: Ember.computed.alias('authors.firstObject')
});

并在模板中将其用作:

{{firstAuthor.name}}