Подтвердить что ты не робот

Создать конфигурационные переменные в sails.js?

Я конвертирую мое приложение из 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, хотя.

4b9b3361

Ответ 1

Вы можете создать свой собственный файл конфигурации в папке 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)