Search code examples
routessails.jsejscustom-routes

Sails.js custom route with same controller but different layouts


today Im here to not just check good answers, but ask! I want to do the following using Sails.js and its routes.js:

My problem picture

What I want is to actually provide different layouts based on the type of user that is logged in. I know how to do that, but I dont want to write this on the routes.js file (because it is messy and I dont want to create controllers to do the job of the route itself):

'get /adminSpace/*' : {
    controller : 'adminSpace' //setting layout on controller
},
'get /userSpace/*' : {
    controller : 'userSpace' // //setting layout on controller
}

A quick way, if possible, would be to write it like this:

'get /[user|admin]/projects/*' : {
    controller : 'project'
    locals: {
      layout: 'based_on_url'
}}

Is this by any way possible?


Solution

  • Okay, I think I'm reading what you want based on the comments - you want different behaviour for normal and admin users. You'll have code to handle this in your routes.js file, and in your views, but you'd like the controllers to get to ignore the difference - they can do their thing without bothering to detect "admin vs normal".

    You can do that by setting locals on two different routes pointing to the same controller:

    'GET /adminSpace/*' : {
        controller : 'UserController',
        locals: {
            admin: true,
            _layoutFile: 'admin'
        }
    },
    'GET /userSpace/*' : {
        controller : 'UserController', // same as above
        locals: {
            admin: false,
            _layoutFile: 'user'
        }
    },
    

    Then in your UserController:

    someAction: function(req, res) {
        // any logic needed
        // can access sails.locals.admin if necessary, but do not have to
        return res.view(); // will use admin.ejs or users.ejs as set in route
    }
    

    In your view, the locals set in the route will still be accessible, and you can add extra locals in the controller if needed. Hope this was what you were looking for!