Get helper in hbs when getting nested object

我怕爱的太早我们不能终老 提交于 2020-01-15 02:55:09

问题


suppose I have the following objects:

image: {
  size: {
    l: {
      url: 'l.jpg',
    },
    m: {
      url: 'm.jpg',
    },
    s; {
      url: 's.jpg',
    }
  }
},
mySize: 'm'

If I want to get corresponding image url in my template, how should I do that? I tried:

{{get image mySize 'url'}}

but it does not work.

I can get the url I want by typing like this:

{{get (get image mySize) 'url')}}

However this is a very unintuitive and ugly workaround. Is there any a better way? Thank you.


回答1:


You need to use the concat helper along with it:

{{get image (concat 'size.' mySize '.url')}}

But this sounds like a job for a computed property:

imageUrl: Ember.computed('mySize', 'image.size', function() {
  let { image, mySize } = this.getProperties('image', 'mySize');
  return Ember.get(image, `size.${mySize}.url`);
})

That way you can just use {{imageUrl}} in the template.

Ember twiddle



来源:https://stackoverflow.com/questions/39116773/get-helper-in-hbs-when-getting-nested-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!