Site editor

Each-in helper


by Ryan Toronto

Today I was working on a feature where I needed to display a list of emojis in a template.

The emojis were stored in a plain JavaScript object on one of my components:

Ember.Component.extend({
  emojis: {
    'thumbsup': { image: 'thumbsup.png', text: 'Thumbs up!' },
    'heart': { image: 'heart.png', text: 'Love it!' }
  }
});

My first thought was to each over the object:

{{#each emojis as |emoji|}}
  {{emoji}}
{{else}}
  Nothing to show
{{/each}}

But this didn't work, because JavaScript objects are not iterateable using the {{#each}} helper. The above template would just always render "Nothing to show".

This is where each-in comes in. It lets us iterate over a JavaScript object:

{{#each-in emojis as |name props|}}
 {{name}}: {{props.text}}
{{/each-in}}

Just what I needed!

Here's a twiddle demonstrating the code.

Questions?

us, or ask in #media on Discord