在sails.js中创建配置变量吗?

问题描述 投票:43回答:2

我正在将我的应用程序从Express转换为sails.js-有什么办法可以在Sails中执行类似的操作?

从Express中的app.js文件中:

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

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

这使我可以在每个视图上访问这些变量,而不必将其硬编码到模板中。不过,不确定在Sails中如何/在哪里做。

node.js express sails.js
2个回答
93
投票

您可以在config/文件夹中创建自己的配置文件。例如带有配置变量的config/myconf.js

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

    anyobject: {
      bar: "foo"
    }
};

然后通过全局sails变量从任何视图访问这些变量。

在视图中:

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

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

在模型中:

// 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)

在控制器中:

注意:这在策略中的工作方式相同。

// 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)

0
投票

我刚刚提供了可提供价值的服务:

maxLimbs: function(){
        var maxLimbs = 15;
        return maxLimbs;
    }
© www.soinside.com 2019 - 2024. All rights reserved.