Let's build an application that shows a list of scientists. To do that, the first step is to create a route. For now, you can think of routes as being the different pages that make up your application.
Ember comes with generators that automate the boilerplate code for common tasks. To generate a route, type this in a new terminal window in your ember-quickstart
directory :
ember generate route scientists
You'll see output like this :
installing route
create app/routes/scientists.js
create app/templates/scientists.hbs
updating router
add route scientists
installing route-test
create tests/unit/routes/scientists-test.js
That is Ember telling you that it has created :
* A template to be displayed when the user visits /scientists
.
* A Route
object that fetches the model used by that template.
* An entry in the application's router (located in app/router.js
).
* A unit test for this route.
Open the newly-created template in app/templates/scientists.hbs
and add the following HTML :
{{page-title "Scientists"}}
<h2>List of Scientists</h2>
In your browser, open http://localhost:4200/scientists
. You should see the <h2>
we put in the scientists.hbs template right below the <h1>
from our application.hbs
template.
Since the scientist route is nested under the application route, Ember will render its content inside the application route template's {{outlet}}
directive.
Now that we've got the scientists template rendering, let's give it some data to render. We do that by specifying a model for that route, and we can specify a model by editing app/routes/scientists.js
.
We'll take the code created for us by the generator and add a model()
method to the Route
:
import Route from '@ember/routing/route';
export default class ScientistsRoute extends Route {
model() {
return ['Marie Curie', 'Mae Jemison', 'Albert Hofmann'];
}
}
This code example uses a feature of JavaScript called classes.
In a route's
model()
method, you return whatever data you want to make available to the template. If you need to fetch data asynchronously, the
model()
method supports any library that uses
JavaScript Promises.
Now let's tell Ember how to turn that array of strings into HTML. Open the scientists
template and add the following code to loop through the array and print it :
<h2>List of Scientists</h2>
<ul>
{{#each @model as |scientist|}}
<li>{{scientist}}</li>
{{/each}}
</ul>
Here, we use the each helper to loop over each
item in the array we provided from the model()
hook. Ember will render the block contained inside the {{#each}}...{{/each}}
helper once for each item (each scientist in our case) in the array. The item (the scientist) that is being rendered currently will be made available in the scientist variable, as denoted by as |scientist|
in the each helper.
The end result is that there will be one <li>
element corresponding to each scientist in the array inside the <ul>
unordered list.