Autoplay

    Creating nested routes in Ember.js

    Iheanyi EkechukwuIheanyi Ekechukwu

    In this lesson, we learn how to create nested routes and templates in an Ember.js application, in addition to how to create nested routes and isolated templates.

    emberEmber.js
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 To get started with nested routes let's generate the parent route. Next, if we go to our router.js file you'll see that the parent route is there. Now, let's go to our parent template file and we can make it be, say, hello parent route. We'll mainly direct to our parent route in the browser and it's there.

    00:33 Next let's go and generate our child route by running ember g route parent/child. If we go to our router.js file we'll see that there's a child route nested within the parent route.

    00:52 If we go to the parent/child.hbs template and we have a header called hello from the child route and save. We can go to our application and go to /parent/child, what we now see is a child template nested within the parent template.

    01:15 To generate a link to the parent, it'll act as normal, just use link to parent route. Then the route's name is parent, and then we save. If we click on this link in the child route it goes back to the parent route and the child template disappears.

    01:33 But if you want to do the same for the child route things get different. Let's go to our parent.hbs file and let's do link to child route. We're going to use the name child, but it won't compile. Because it's nested, we actually have to preface it with parent, then use dot and then save. Now the link renders properly and if we click on it, it navigates to the child route and nested within the parent template.

    02:08 Sometimes you want to have that nested URL structure but you don't want to have the nested template thing going on. In order to change this we have to do three things. First we'll go to our router.js file and we're going to take this child route and put it outside the parent route.

    02:24 Then we're going to change its name from child to parent.child so we don't break our UR links. Then third we're going to define an object as the second argument and route. Pass in the path attribute and set it to parent/child, and then save.

    02:49 Now you'll see we have hello from the child route but the parent template has disappeared. If we click on the parent route link we get the parent route. We can click on the child route link again and they're isolated from one another.

    Discuss

    Discuss