2015-04-03 15 views
2

我很難嘗試傳遞一個對象到我的項目的佈局,以獲得我需要在導航欄中顯示的類別列表。我一直在嘗試幾個解決方案,所有這些都涉及到使用策略和分配res.locals.myVar = someObj,問題是res.locals和也使用req.options.locals.myVar只能在控制器操作中使用視圖而不是佈局傳遞一個對象到views/layout.ejs在sails.js

到目前爲止,我得到了這個。

// 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 %> 

回答

0

我認爲其確定使用政策來保存數據到res.locals,但在我的實現中,我將數據保存到請求本身併發送到控制器中的視圖(它看起來更清晰的對我來說)

配置/策略/ getCategories

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

API /控制器/ ABCController.js

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

配置/ policies.js

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

**配置/ routes.js

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

這裏的問題是,我不希望任何特定的視圖來處理導航欄類別。 「導航欄」在佈局中。 – adavia 2015-04-03 05:15:45

+0

在這種情況下,您的解決方案更好,我認爲,使每個請求都有相同的策略來保存res.locals變量 – 2015-04-03 06:52:03

+0

那麼問題是我的解決方案不會適用於這種情況。 – adavia 2015-04-03 15:49:20

相關問題