AJP
AJP

Reputation: 545

Ember js display each item in javascript array in {{#each}} helper

I am creating the following array variable in an ember component, and passing it to the controller for my template file.

let errors = [
  "Line 2 needs a tab separator.",
  "Line 42 is empty.",
  "Line 43 is empty.",
  "Line 44 is empty.",
  "Line 45 is empty.",
  "Line 46 is empty.",
  "Line 47 is empty."
];

In the controller I am setting a property to this array value:

this.set('errorList', errors);

I can then display the array in the template file:

{{controller.errorList}}

The problem is that the errors display as one long string like so:

Line 2 needs a tab separator.,Line 42 is empty.,Line 43 is empty.,Line 44 is empty.,Line 45 is empty.,Line 46 is empty.,Line 47 is empty.

Is it possible to use an {{#each}} helper to display each item, and thus become able to to add in HTML tags- eg:

<ul>
{{#each **** as |***|}
 <li>***Display each individual error here.***</li>
{{/each}}
</ul>

Would it help if I was able to convert the array variable into a JSON object?

Upvotes: 2

Views: 559

Answers (1)

runspired
runspired

Reputation: 2693

Yes, this is the correct syntax:

<ul>
{{#each errorList as |error|}
  <li>{{error}}</li>
{{/each}}
</ul>

If you were defining your array as above, you also have a bunch of syntax errors. The array should look like this.

let errors = [
  "Line 2 needs a tab separator.",
  "Line 42 is empty.",
  "Line 43 is empty.",
  "Line 44 is empty.",
  "Line 45 is empty.",
  "Line 46 is empty.",
  "Line 47 is empty."
];

If you are using Ember pre-glimmer (e.g. < 1.13.x), you also need to use an instance of an Ember.Array instead of a native array if you have prototype extensions disabled. You can do that just by wrapping the errors array like this.

let errors = Ember.A([ ... the same as before ... ])

Upvotes: 1

Related Questions