43

我正在将我的应用程序从 Express 转换为sails.js - 有没有办法在 Sails 中做这样的事情?

来自我app.js在 Express 中的文件:

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

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

这让我可以在每个视图上访问这些变量,而无需将它们硬编码到模板中。不过,不确定如何/在哪里可以在 Sails 中进行操作。

4

2 回答 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 %>

服务中

// 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)
于 2013-08-16T13:05:40.110 回答
0

我刚刚做了一项提供价值的服务:

maxLimbs: function(){
        var maxLimbs = 15;
        return maxLimbs;
    }
于 2020-05-29T20:11:06.630 回答