Rodrigo Montano Rodrigo Montano - 2 years ago 198
Node.js Question

SailsJS proper way to pass an object/variable to a layout view

Hello I was wondering if there is a proper way to pass a variable or object to a layout view?

This is what I'm doing at the moment and it works

index: function(req, res){
res.view({ layout: 'mylayout', myvar: 'This is a view var' });

But on every action I have to define 'myvar' so I can use it at the layout level, so what I would like to know if there is some kind of controller or action for layouts so I can place there my logic?

Answer Source

Actually starting with Sails v0.10-rc5, you can use sails.config.views.locals hash to specify variables that should be provided by default to all views. So in config/views.js, something like:

   locals: {
      myvar : 'this is a view var'

would add the var to every view. This is mostly useful for variables that affect the view engine; see here for more details.

You can also use a policy in Sails v0.10.x to set vars across multiple views, by altering req.options.locals. So if you created a policy /api/policies/decorate.js with:

module.exports = function(req, res, next) {

   // Default to an object if empty, or use existing locals that may have
   // been set elsewhere
   req.options.locals = req.options.locals || {};

   // Set a new local var that will be available to any controller that
   // implements the policy
   req.options.locals.myVar = Math.random()

and then set up your /config/policies.js with something like:

 module.exports = {

    '*': 'decorate'


then any controller action that uses res.view will have that myVar variable available in the view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download