Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 841
Rodrigo Montano Avatar asked Apr 15 '14 17:04

Rodrigo Montano


1 Answers

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.

like image 111
sgress454 Avatar answered Sep 23 '22 13:09

sgress454