在handlebars模板中显示hasMany ember关系中的第一个项目 [英] Display the first item in hasMany ember relationship in handlebars template
问题描述
我需要在hasMany关系中显示第一个项目
I need to display the first item in an hasMany relationship
基本上一个线程可能有超过1个作者,但是我只需要显示一个特定的模板
Basically a thread could have more than 1 author but I need to display only the first one in a particular template
我有以下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
根据句柄语法,但没有改变。
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提前为您的帮助
Thnx in advance for your help
推荐答案
使用Ember.Enumerable的 firstObject
:
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 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}}
这篇关于在handlebars模板中显示hasMany ember关系中的第一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!