Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple layout within a SailsJS app?

My Sails.js application have separate frontend and admin layout. My view engine is ejs.

How do I use separate layouts for frontend and admin site?

Can I use specific layout for each action?

like image 587
anhnt Avatar asked Jan 07 '14 04:01

anhnt


4 Answers

From Sails.js Documentation:

At least in EJS, instead of indicating your custom layout with the layout local, you must use _layoutFile:

res.view({
  _layoutFile: 'relativePathToYourCustomLayoutFromTheTargetView.ejs'
});

The path to the layout you're wanting to use should be specified relative to the view you're rendering. So if you're in the create action of the UserController, rendering a view (views/user/create.ejs), the relative path to your custom layout might be: ../staticSiteLayout.ejs

PROJECT FOLDER
└── views
    ├── staticSiteLayout.ejs
    ├── layout.ejs
    └── user
        └── create.ejs

UPDATE:

Seems like the documentation is a bit off from the code, so for the current (v0.9.8) version the way to go is the following:

module.exports = { 
  index: function(req, res){
    res.view({ layout: 'layoutadmin' });
  }
}
like image 194
bredikhin Avatar answered Nov 16 '22 10:11

bredikhin


In Sails 0.10 you can set a different layout like this in your controller:

// override the layout to use another
    res.locals.layout = 'layouts/layout2';
    return res.view('test');

Detailed explanation here.

like image 25
Melvin Avatar answered Nov 16 '22 12:11

Melvin


In Sails v0.12, if you need to set layout in your controller, you might create a new folder (e.g. "layout") and push layout files.

res.view('auth/login', {layout: layout/my_file_layout}

you can also do:

res.locals.layout = "layout/my_file_layout";
res.view('auth/login');
like image 2
WikeC Avatar answered Nov 16 '22 12:11

WikeC


Sorry for spamming your question but i need a similar solution for my app. It would be wonderful to define layouts in routes.js so for example /admin/* would use one layout, and eg. /app/* would use the other, etc. Because it's a pita do dive into controllers and overspam them with static layout paths. I tried this concept but it seems to be working only if I also define a controller in the routes.js config file eg:

module.exports.routes = {

   '/admin/*' : {
      controller: 'AdminController',
      action: 'index',
      locals: {
         layout: 'admin/layout'
      }
   }
};

This does work, but is routing all actions for admin into the same controller, which is of course wrong. If I omit the controller part, that concept is always using the default view/layout.ejs and the local is not set:

module.exports.routes = {

   '/admin/*' : {
      locals: {
         layout: 'admin/layout'
      }
   }
};

This doesn't work but it would be ideal to get it that way.

like image 1
cybercow Avatar answered Nov 16 '22 12:11

cybercow