expressjs有条件的视图渲染path

我正在使用expressjs编写一个应用程序。 我通常在/ views文件夹中有我的意见。 它们覆盖了我客户90%的需求,但有时我必须重写这些视图中的一个或另一个来添加定制function。 我真的不知道我可以build立一个如下的文件夹结构:

*{ ...other expressjs files and folders...}* /views view1.jade view2.jade view2.jade /customerA view2.jade /customerB view3.jade 

我想要重写expressjs的response.render()函数来应用以下algorithm的行为:

 1. a customer requests a view 2. if /{customer_folder}/{view_name}.jade exists, than render /{customer_folder}/{view_name}.jade else render /views/{view_name}.jade 

因此,对于customerAresponse.render('view1')将引用/views/view1.jaderesponse.render('view2')将引用/customerA/view2.jade (那些使用appcelerator的titanium可能听起来很熟悉)

我想要一个优雅的方式来实现这个行为, 而不用修改expressjs的核心function,因此可能会得到升级我的框架的麻烦。 我想这是一个普遍的问题,但我无法在网上find任何文章。

你可以挂接http.ServerResponse.render

以下是我头顶的一些代码,用作中间件:

 var backup = res.render res.render = function() { //Do your thing with the arguments array, maybe use environment variables backup.apply(res, arguments) //Function.prototype.apply calls a function in context of argument 1, with argument 2 being the argument array for the actual call } 

我会创build一个自定义View类:

 var express = require('express'); var app = express(); var View = app.get('view'); var MyView = function(name, options) { View.call(this, name, options); }; MyView.prototype = Object.create(View.prototype); MyView.prototype.lookup = function(path) { // `path` contains the template name to look up, so here you can perform // your customer-specific lookups and change `path` so that it points to // the correct file for the customer... ... // when done, just call the original lookup method. return View.prototype.lookup.call(this, path); }; app.set('view', MyView); 
Interesting Posts