2014-03-02 46 views
0

我知道可以通过做这样的事情通过一个模型中表达一个观点:是否可以将模型传递给Express中的布局?

exports.locations = function(req, res){ 
    Location.find(function(err, results) { 
     res.render('locations', { title: 'Locations', locations: results }); 
    }); 
}; 

但是是有可能的模型传递给我的布局?

+1

当你说你的“布局”是指你的意思,例如你在视图中用'extends layout'扩展的通用'layout.jade'?如果是这样,你的布局可以访问你传递给'render()'的模型。或者我误解了你的问题? –

+0

不,你是对的。我希望作为布局的一部分访问每个视图的文档,现在我必须在每个路径中传递这些文档。有没有更简单的方法来做到这一点? – drewwyatt

+0

所以你真正要问的是,如果有一种方法可以有一个'模板'模型对象,可以这么说,预先填充了一些'全局'项目,并且只需要扩展你的页面特定内容? –

回答

1

假设你有一个单一的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之一,extendassign或类似的函数库,如lodash,下划线等。参见doc for lodash.assign(),它说明完成同样的事情。

UPDATE还有一种方法。

您可能还想查看Express'app.locals documentation - 它可能适合您。

+0

这是比我一直在做的更优雅。谢谢!!!! – drewwyatt

+0

非常欢迎你;很高兴这很有帮助。请注意,我刚刚发布了一个提及Express''app.locals'的编辑,也是另一种方法。祝你有个愉快的一周。 –

相关问题