Often, you'll have a list of items that you'll need to iterate over. We can iterate through these items with the each
helper. This recipe will go over how to do this.
Let's say that we have a list of students and want to display them in our template. We'll use the each
helper to accomplish this.
student
controller
and template
:$ ember g template student $ ember g controller student
This will create the necessary files needed for our example.
router.js
file with the new student
route:// app/router.js … Router.map(function() { this.route('student'); });
This will add a new conditional
route. To access this route using the Ember server, open a web browser and navigate to http://localhost:4200/student
.
students
as a property:// app/controllers/students.js import Ember from 'ember'; export default Ember.Controller.extend({ students: [ {name: 'Erik'}, {name: 'Jim'}, {name: 'Jane'}] });
This array has three student objects.
student.hbs
template, we'll iterate through the students
array using the each
helper:// app/templates/student.hbs {{#each students as |student|}} {{student.name}}<br> {{/each}}
The first argument to the each
helper is the array to be iterated over. In this case, this is the students
array that was declared in the student
controller. The |student|
block param
is what we'll use to iterate over the array.
The each
helper must be in the block form. In this example, each value of the student will be displayed with an HTML break afterward.
Erik<br> Jim<br> Jane<br>
If, by chance, the array was empty, you can use {{else}}
.
// app/templates/student.hbs {{#each emptyArray as |item|}} {{item}} {{else}} Empty Array {{/each}}
The else
block will be rendered only if the array is empty or doesn't exist.
If needed, you can also access index
of the array in the second block param
.
index
block param
:// app/templates/student.hbs {{#each students as |student index|}} Student {{student.name}} is at index {{index}}<br> {{/each}}
After each iteration, name
and index
is displayed with an HTML break element. The index can be accessed using the double curly braces {{index}}
.
Student Erik is at index 0<br> Student Jim is at index 1<br> Student Jane is at index 2<br>
Keep in mind that index
starts at 0
and not 1
.
The each
helper uses block params to iterate through arrays. The each
helper takes an array argument and the block param
is used to iterate each individual item on the list. If the array doesn't exist or is empty, you can use else
to display a message instead.
In the recipes in this chapter, the students
array was declared in controller
. It had several student objects that could be accessed by the template. The template used this array and iterated over it with the each
helper.