我知道可以通過做這樣的事情通過一個模型中表達一個觀點:是否可以將模型傳遞給Express中的佈局?
exports.locations = function(req, res){
Location.find(function(err, results) {
res.render('locations', { title: 'Locations', locations: results });
});
};
但是是有可能的模型傳遞給我的佈局?
我知道可以通過做這樣的事情通過一個模型中表達一個觀點:是否可以將模型傳遞給Express中的佈局?
exports.locations = function(req, res){
Location.find(function(err, results) {
res.render('locations', { title: 'Locations', locations: results });
});
};
但是是有可能的模型傳遞給我的佈局?
假設你有一個單一的js文件裏面所有(相關)的路線,你可以添加一個功能是這樣的:
function applyGlobals(pageModel) {
pageModel.myGlobalThing = "I'm always available";
pageModel.anotherGlobalThing = 8675309;
return(pageModel);
}
exports.locations = function(req, res){
Location.find(function(err, results) {
res.render('locations', applyGlobals({ title: 'Locations', locations: results }));
});
};
您還可以創建一個更一般化的解決方案:
function Globalizer(baseContent) {
var theFunc = function(specificContent) {
var keys = Object.keys(baseContent);
for (var i = 0; i < keys.length; i++)
{
// the lets the page content override global content by not
// overwriting it if it exists;
if(!specificContent.hasOwnProperty(keys[i])){
specificContent[keys[i]] = baseContent[keys[i]];
}
}
return specificContent;
};
return theFunc;
};
// And use it like so.
var applyGlobals = new Globalizer({global1: 12, global2: 'otherthing'});
var pageVars = applyGlobals({item1: 'fifteen', 'item2': 15, global2: 'override'});
console.log(require('util').inspect(pageVars));
它會發射:
{ item1: 'fifteen',
item2: 15,
global2: 'override',
global1: 12 }
同樣,您可以使用各種mixin
之一,extend
assign
或類似的函數庫,如lodash,下劃線等。參見doc for lodash.assign()
,它說明完成同樣的事情。
UPDATE還有一種方法。
您可能還想查看Express'app.locals
documentation - 它可能適合您。
這是比我一直在做的更優雅。謝謝!!!! – drewwyatt
非常歡迎你;很高興這很有幫助。請注意,我剛剛發佈了一個提及Express''app.locals'的編輯,也是另一種方法。祝你有個愉快的一週。 –
當你說你的「佈局」是指你的意思,例如你在視圖中用'extends layout'擴展的通用'layout.jade'?如果是這樣,你的佈局可以訪問你傳遞給'render()'的模型。或者我誤解了你的問題? –
不,你是對的。我希望作爲佈局的一部分訪問每個視圖的文檔,現在我必須在每個路徑中傳遞這些文檔。有沒有更簡單的方法來做到這一點? – drewwyatt
所以你真正要問的是,如果有一種方法可以有一個'模板'模型對象,可以這麼說,預先填充了一些'全局'項目,並且只需要擴展你的頁面特定內容? –