Get helper in hbs when getting nested object

2019-07-09 22:56发布

问题:

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