我设置了一个简单的 Handlebars 模板,显示模型记录中的图像。以下内容按预期工作,并使用每个项目上的 imageURL 来显示图像。
{{#each this}}
<img {{bindAttr src="imageURL"}} >
{{/each}}
但是,我还想显示记录集中的第一张图像。走过How do I access an access array item by index in handlebars?我添加了以下内容,但没有成功。
<img {{bindAttr src="this.0.imageURL"}} >
我也尝试了以下方法,但也没有成功。
{{#with this.[0]}}
<img {{bindAttr src="imageURL"}} >
{{/with}}
有什么想法吗?
值得注意的地方:Ember 1.2.0、Handlebars 1.2.0、jQuery 1.10.2
最佳答案
这不起作用的原因是 this
引用了呈现此模板的 ArrayController
。现在您可能想知道为什么 {{#each this}}
有效。这是因为 Ember 将获取数组 Controller 的 content
属性,这是一个包含实际图像对象的 Ember.Array
。
请阅读有关 Ember.ArrayController 的文档:http://emberjs.com/api/classes/Ember.ArrayController.html .
为了显示第一张图像,您可以像这样扩展 Controller :
App.IndexController = Ember.ArrayController.extend({
firstImage: function() {
this.get('firstObject');
}.property('[]')
});
您必须使用 this.get('firstObject')
因为 Ember.Array 的工作方式与普通 js 数组有点不同。在这里您可以找到更多文档:http://emberjs.com/api/classes/Ember.Array.html#property_firstObject 。
显示模板中的第一张图像现在变得很容易:
<img {{bindAttr src="firstImage.imageURL"}} />
关于javascript - Handlebars 数组元素在此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892620/