Search code examples
ember.jshandlebars.js

Is there a way to define and iterate over an array in ember handlebars templates?


I'm working on a styleguide and need to iterate over an array in a handlebars template.

I know that you can iterate over objects or other variables when passed into a template, but is there a way to iterate over a collection defined in the template? I think this breaks the "no-logic in views" concept that handlebars pushes, but I imagine this is a common use case.

{{#each ['success', 'warning', 'error', 'info'] key="@index" as |type|}}
  <div class='banners-container'>
    <div class='content'>
      <div class='banner banner-{{type}} has-icon has-dismiss'>
        <p>Banner {{type}}</p>
      </div>
    </div>
  </div>
{{/each}}

I would expect this to output 4 collections of the banners-container elements, but it's not outputting anything.

What's the best way to handle this use case?


Solution

  • You can use array helper from ember-composable-helpers to compose arrays directly in the template:

    {{#each (array 1 2 3) as |numbers|}}
      {{numbers}}
    {{/each}}