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.
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.
<!-- views/foo/bar.ejs -->
<%= sails.config.myconf.name %>
<%= sails.config.myconf.author %>
// 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
// 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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With