[英]Passing an object to views/layout.ejs in sails.js
我很难将一个对象传递到项目的布局中,以便获得我需要在导航栏中显示的类别列表。 我在这里尝试了几种解决方案,所有解决方案都与使用策略和分配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'
//在layout.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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.