简体   繁体   English

在把手模板中显示hasMany余烬关系中的第一项

[英]Display the first item in hasMany ember relationship in handlebars template

I need to display the first item in an hasMany relationship 我需要在hasMany关系中显示第一个项目

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 我有以下的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. 现在在我的模板中,我想做一些像{{thread.authors[0].fullname}}这样的东西,但它不起作用。 I've tried also thread.authors.0.fullname according to the handlebars syntax but nothing changed. 我根据把手语法尝试了thread.authors.0.fullname但没有改变。

Thnx in advance for your help Thnx提前为您提供帮助

Use Ember.Enumerable's firstObject : 使用Ember.Enumerable的firstObject

{{thread.firstObject.fullName}}

If you are going to use it in a lot of places, its best to define it as a computed property in the model: 如果要在很多地方使用它,最好将其定义为模型中的计算属性:

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

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

and use it in your templates as: 并在模板中使用它:

{{firstAuthor.name}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM