【问题标题】:Passing an object to views/layout.ejs in sails.js在sails.js 中将对象传递给views/layout.ejs
【发布时间】:2015-04-03 01:38:12
【问题描述】:

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

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

// 获取房间列表策略

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'

// 在 layout.ejs 中

<%= roomlist %>

【问题讨论】:

    标签: javascript node.js sails.js


    【解决方案1】:

    我认为使用策略将数据保存到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"
    }
    

    【讨论】:

    • 这里的问题是我不希望任何特定的视图来处理导航栏类别。 “导航栏”在布局中。
    • 在这种情况下,我认为你的解决方案更好,让每个请求都有相同的策略来保存 res.locals 变量
    • 那么问题是我的解决方案不适用于这种情况。
    • 真的吗?这个对我有用。您是否尝试在控制器中打印res.locals?也许提供您正在使用的 Sails 版本会有所帮助
    猜你喜欢
    • 2015-05-29
    • 2013-08-16
    • 2015-12-09
    • 2020-04-26
    • 2016-05-09
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多