Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create config variables in sails.js?

I'm converting an app of mine from Express to sails.js - is there a way I can do something like this in Sails?

From my app.js file in Express:

var globals = {
    name: 'projectName',
    author: 'authorName'
};

app.get('/', function (req, res) {
    globals.page_title = 'Home';
    res.render('index', globals);
});

This let me access those variables on every view without having to hardcode them into the template. Not sure how/where to do it in Sails though.

like image 785
user2688473 Avatar asked Aug 16 '13 07:08

user2688473


1 Answers

You can create your own config file in config/ folder. For example config/myconf.js with your config variables:

module.exports.myconf = {
    name: 'projectName',
    author: 'authorName',

    anyobject: {
      bar: "foo"
    }
};

and then access these variables from any view via global sails variable.

In a view:

<!-- views/foo/bar.ejs -->
<%= sails.config.myconf.name %>
<%= sails.config.myconf.author %>

In a service

// api/services/FooService.js
module.exports = {

  /**
   * Some function that does stuff.
   *
   * @param  {[type]}   options [description]
   * @param  {Function} cb      [description]
   */
  lookupDumbledore: function(options, cb) {

    // `sails` object is available here:
    var conf = sails.config;
    cb(null, conf.whatever);
  }
};

// `sails` is not available out here
// (it doesn't exist yet)
console.log(sails);  // ==> undefined

In a model:

// api/models/Foo.js
module.exports = {
  attributes: {
    // ...
  },

  someModelMethod: function (options, cb) {

    // `sails` object is available here:
    var conf = sails.config;
    cb(null, conf.whatever);
  }
};

// `sails is not available out here
// (doesn't exist yet)

In a controller:

Note: This works the same way in policies.

// api/controllers/FooController.js
module.exports = {
  index: function (req, res) {

    // `sails` is available in here

    return res.json({
      name: sails.config.myconf.name
    });
  }
};

// `sails is not available out here
// (doesn't exist yet)
like image 154
ataman Avatar answered Oct 14 '22 01:10

ataman