【问题标题】:Handlebars Array Element on ThisHandlebars Array Element on this
【发布时间】:2014-01-02 21:52:27
【问题描述】:

我设置了一个简单的车把模板来显示来自模型记录的图像。以下按预期工作,并使用每个项目上的 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

【问题讨论】:

    标签: javascript ember.js handlebars.js


    【解决方案1】:

    这不起作用的原因是this 引用了渲染此模板的ArrayController。现在您可能想知道为什么{{#each this}} 有效。这是因为 Ember 将获取数组控制器的 content 属性,这是一个包含实际图像对象的 Ember.Array

    请阅读 Ember.ArrayController 上的此文档:http://emberjs.com/api/classes/Ember.ArrayController.html

    为了显示第一张图片,您可以像这样扩展控制器:

    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"}} />
    

    【讨论】:

    • 感谢您的帮助。我还发现以下方法也有效。
    【解决方案2】:

    它似乎有效:

    模板:

    <script type="text/x-handlebars" data-template-name="index">
      <ul>
      {{#each this}}
        <img {{bindAttr src="this.0.imageURL"}} >
      {{/each}}
      </ul>
    </script>
    

    JS:

    App = Ember.Application.create();
    
    App.IndexRoute = Ember.Route.extend({
      model: function() {
        return [
                 [
                   {imageURL: "http://placehold.it/100x100"},
                   {imageURL: "http://placekitten.com/200/200"}
                 ], 
                 [
                   {imageURL: "http://placehold.it/200x200"},
                   {imageURL: "http://placekitten.com/100/100"}
                 ],
                 [
                   {imageURL: "http://placehold.it/300x300"},
                   {imageURL: "http://placekitten.com/300/300"}
                 ]
               ];
      }
    });
    

    JSBin example

    【讨论】:

      【解决方案3】:

      如果您转到 Try Handlebars.js 并添加到 Handlebars 模板 {{this.0.img}}上下文(JavaScript 文字或 JSON)

      [{
         img: 'path/to/img'
      }, {
         img: 'path/to/img'
      }]
      

      它的工作。也许你的助手有问题。

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 2013-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        相关资源
        最近更新 更多