Defining routes with templates

Another job of the route handler is rendering the appropriate template. Here is a recipe that goes over this.

How to do it...

In this recipe, we'll create a few nested routes and check where they get rendered.

  1. In a new project, create a new students and schools route:
    $ ember g route schools
    $ ember g route schools/students
    

    This will create the nested students and schools route.

  2. Let's take a look at the router.js file:
    // app/router.js
    import Ember from 'ember';
    import config from './config/environment';
    
    var Router = Ember.Router.extend({
      location: config.locationType
    });
    
    Router.map(function() {
      this.route('schools', {}, function() {
        this.route('students', {});
      });
    });
    
    export default Router;

    The generated command already created the routes that we need. The schools route has a nested route called students.

    By convention, the route will render the template with the same name. Therefore, the schools route will render to the schools.hbs file while the students route will be rendered to the schools/students.hbs file.

  3. Update the schools.hbs file:
    // app/templates/schools.hbs
    This is the school route<br>
    {{outlet}}

    The {{outlet}} will render the students.hbs file in the schools folder. Every template will be rendered to {{outlet}} of its parent route's template.

  4. Update the students.hbs file in the app/templates/schools folder:
    // app/templates/schools/students.hbs
    This is the students route<br>
    {{outlet}}
  5. Run ember server and you should see this result:
    How to do it...
  6. By visiting http://localhost:4200/schools/students, both the templates are displayed. The application {{outlet}} renders the school template. The school template's {{outlet}} renders the students template.
  7. If required, you can change where the route renders. Instead of rendering in the template with the same name, you can set it to anything using the renderTemplate() method in the route handler:
    // app/routes/school.js
    import Ember from 'ember';
    
    export default Ember.Route.extend({
      renderTemplate() {
        this.render('anotherSchool');
      }
    });

    The school route will now render to the anotherSchool template.

How it works...

Routes, by default, will render a template based on the same name as the route. Ember does this by convention. On the other hand, using renderTemplate in the route handler can change this default. This is all done under the hood by the Ember API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset