将对象传递到sails.js中的views/layout.ejs



为了获得需要在导航栏中显示的类别列表,我很难将对象传递到项目的布局中。我在这里尝试了几个解决方案,它们都与使用策略和分配res.locals.myVar=someObj有关,问题是res.locals和使用req.options.locals.myVar只能在控制器操作的视图中使用,而不能在布局中使用

到目前为止,我得到了这个。

//getRoomList策略

Room.find().exec(function(err, rooms) {
    if (err) {
        return res.badRequest('Something went wrong.');
    }
    if (rooms) {
        res.locals.roomlist = rooms;
        next();
    } else {
        res.notFound();
    }
});

//配置/策略

'*': 'getRoomList'

//在布局.ejs

<%= roomlist %>

我认为使用策略将数据保存到res.locals中是可以的,但在我的实现中,我将数据保存在请求本身,并将其发送到控制器中的视图(我看起来更清楚)

config/policies/getCategories

module.exports = function(req, res, next){
  Categories.find().exec(function(err, models) {
      if (err) return res.badRequest("Error");
      req.categories = models;
      next();
  });
}

api/controllers/ABCController.js

module.exports = {
   index : function(req, res, next){
      res.view('page/index', {
          categories : req.categories
      });
    }
}

config/policies.js

ABCController : {
   index: ['getCategories', 'getProfiles']
   // add this policy to any page who needs nav bar categories
}

**config/routes.js

'/home/': {
  controller: "ABCController",
  action: "index"
}

最新更新