是否可以将模型传递给Express中的布局?

时间:2014-03-02 20:02:20

标签: node.js mongodb express mongoose

我知道可以通过这样的方式将模型传递给express中的视图:

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

但是可以将模型传递给我的布局吗?

1 个答案:

答案 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 }

同样,您可以使用各种mixinextend assign或其他类似函数之一,例如lodash,下划线等。请参阅doc for lodash.assign(),其中说明了完成同样的事情。

更新另一种方法。

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