Search code examples
javascriptember.jsember-cli

Templates on dynamic segments


I have a requirement to make what is essentially a dynamic form (wizard) that has multiple steps. Now I want to be able to quickly add new steps to the wizard in the future (or remove them) so I don;t to create separate routes for each step like so:

this.resource('wizard', { path: '/' }, function() {
  this.route('step1', { path: '/' });
  this.route('step2');
  this.route('step3');
  this.route('step4');
  this.route('step5');
});

I would much prefer to have a dynamic segment that takes in the name of the step and loads the corresponding template of the same name, like so

this.resource('wizard', { path: '/' }, function() {
  this.route('step', { path: '/:step' });
});

Is this at all possible or is this just wishful thinking.


Solution

  • I have come up with a solution but I am not sure it is considered the best...

    I have defined a route in the router to take in a dynamic segment with the name of the template:

    this.resource('wizard', { path: '/wizard' }, function() {
      this.route('missing', { path: '/:step' });
    });
    

    I have then created a missing route that takes this dynamic segment from the model and uses it to load in the template into the appropriate outlet

    export default Ember.Route.extend({
      renderTemplate: function(controller, model) {
        this.render('wizard/' + model.step, {
          controller: controller
        });
      }
    });
    

    I would love to hear some thoughts on this solution.