How to handle more than one model into a template/route in ember.js?

Member

by gilbert , in category: Javascript , 3 months ago

How to handle more than one model into a template/route in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 3 months ago

@gilbert 

In Ember.js, you can handle multiple models in a template or route by using the model hook in the route file and then passing in multiple models in the renderTemplate method.


Here is an example of how to handle multiple models in a single route/template in Ember.js:

  1. Define the models in the route file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// routes/example-route.js

import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return Ember.RSVP.hash({
      model1: this.store.findAll('model1'),
      model2: this.store.findAll('model2')
    });
  }
});


  1. Use the renderTemplate method in the route to pass in multiple models to the template:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// routes/example-route.js

import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return Ember.RSVP.hash({
      model1: this.store.findAll('model1'),
      model2: this.store.findAll('model2')
    });
  },

  setupController(controller, models) {
    this._super(controller, models);
    for (let key in models) {
      controller.set(key, models[key]);
    }
  },

  renderTemplate() {
    this.render('example-template', {
      into: 'application',
      model1: this.modelFor('example-route').model1,
      model2: this.modelFor('example-route').model2
    });
  }
});


  1. Access the models in the template:
1
2
3
4
5
6
7
8
9
<!-- templates/example-template.hbs -->

{{#each model1 as |model1Item|}}
  <!-- Display model1 data here -->
{{/each}}

{{#each model2 as |model2Item|}}
  <!-- Display model2 data here -->
{{/each}}


By following these steps, you can handle multiple models in a single route/template in Ember.js. You can access each model separately in the template and display their data as needed.