使用Sails.js中的自定义数据和过滤器扩展所有视图

时间:2015-07-31 21:43:08

标签: templates view sails.js

我正在开发一个Sails.js应用程序,我想用自定义数据和函数扩展所有视图。

这样做的最佳方法是什么?

我尝试创建一个策略来执行此操作,但策略仅适用于具有控制器的路由。

1 个答案:

答案 0 :(得分:1)

自定义数据

您可以使用自定义挂钩来实现此目的。

使用以下内容在指定路径api/hooks/viewsGlobals/index.js创建文件:

module.exports = function viewsGlobals (sails) {
  return {
    routes: {
      before: {
        // This middleware will be executed for every request.
        '*': function (req, res, next) {

          // Using condition to filter out static file requests.
          if (req.accepted.some(function (type) {
            return type.value === 'text/html';
          })) {
            res.locals.someData = {
              // Place your custom data here.
            };
          }

          return next();
        }
      }
    }
  }
};

自定义过滤器

按以下路径创建文件:config/view-filters/toUpper.js和以下内容:

// Replace this with templating engine that you use.
var swig = require('swig');

// Use the API of your templating engine to add custom filter.
swig.setFilter('toUpper', function (value) {
  return value.toUpperCase();
});
相关问题