Search code examples
javascriptbackbone.jsmarionette

How to ignore trailing slash in marionette routes?


I am defining routes in Marionettejs as follows:

var Mn = require('backbone.marionette');

var Router = Mn.AppRouter.extend({
    routes: {
        '': 'default',
        'login': 'login',     // http://localhost:8080/#/login
        'signup': 'signup'    // http://localhost:8080/#/signup
    }, 
    initialize: function () {
        var initData = this.getOption('keyInOptions');
    },
    // below are route functions
    default: function () {
        console.log('this is default route');
    }, 
    login: function () {
        console.log('this is login route');
    },
    signup: function () {
        console.log('this is signup route');
    }
});

module.exports = Router;

Then in the browser:

http://localhost:8080/#/login

successfully triggers the login route, but

http://localhost:8080/#/login/

(add one forward slash at the end) will not trigger login route function. I know I can define another route entry:

...
'login': 'login',
'login/': 'login',
...

to solve this problem, but this solution will double the entries in router definition. Is there a better way to trigger the same route handler for login and login/ ?


Solution

  • Have you tried surrounding the trailing slash with parentheses? Like the following:

    routes: {
        'login(/)': 'login'
    }
    

    From the backbone documentation:

    Part of a route can be made optional by surrounding it in parentheses (/:optional).