Dynamic Segments (Optional)


#1

I have a use case and I’m not sure if there is an easy solution within the current Ember router or not, is there a way to define an optional routing param?

I would like to have a dynamic route that might have 1 or might have 2 segments, and then further routes nested inside. My idea of the structure would be something like the below (except the :topic part would be optional)

this.route('course', { path: '/:course' }, function() {
  this.route('page', { path: '/:topic/:page' }, function() {
    this.route('menu', function() {

    });
  });
});

/my-course/my-topic/my-page would hit the page route

/my-course/my-page would hit the page route

/my-course/my-page/menu would hit the menu route

/my-course/my-topic/my-page/menu would hit the menu route


#2

One solution I have found is to use the wildcard and then break the segments down myself.

this.route('course', { path: '/:course' }, function() {
  this.route('page', { path: '/*path_for_page' }, function() {
    this.route('menu', function() {

    });
  });
});

#3

Your solution with the wildcard seems pretty reasonable.

I think the other choice if you wanted to be more static would be to repeat the routes. You can avoid repeating their implementations by re-exporting their files under their new names. Like

// app/routes/topic-without-page.js
export { default } from './topic';

(Re-exporting works for templates too.)

This is obviously more verbose than your solution, so unless you run into a problem with it I would keep it.