nfisher
nfisher

Reputation: 57

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?

Upvotes: 0

Views: 1482

Answers (2)

Denis Nazarenko
Denis Nazarenko

Reputation: 164

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

Upvotes: 7

rinold simon
rinold simon

Reputation: 3052

you can define your array in your controller/component files and use that property in hbs. say

app/controllers/application.js

import Controller from '@ember/controller';
import { A } from '@ember/array';

export default Controller.extend({
  status: A(['success', 'warning', 'error', 'info']),
})

in your app/templates/application.hbs

{{#each status as |type|}}
  {{type}}
{{/each}}

You can have a look at ember native array function

Upvotes: 0

Related Questions