javascript - expressjs条件 View 渲染路径

标签 javascript node.js express pug overriding

我正在使用expressjs编写一个应用程序。我的 View 通常位于 /views 文件夹中。它们满足了 90% 的客户需求,但有时我必须覆盖其中一个或另一个 View 以添加定制功能。我真的想知道我可以构建一个像这样的文件夹结构:

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

我想要的是覆盖expressjs的response.render()函数的行为以应用以下算法:

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钛金属的人可能听起来很熟悉)

我想要一种优雅的方式来实现此行为,没有修改expressjs核心功能的麻烦,因此可能在升级我的框架时得到处理。我想这是一个常见问题,但我在网上找不到任何文章。

最佳答案

我将创建一个自定义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);

关于javascript - expressjs条件 View 渲染路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303440/

相关文章:

javascript - jquery 滚动条没有出现在 Firefox 中

javascript - 禁用 IOS Safari 弹性滚动

javascript - Protractor browser.get() 无法导航到带有 fatal error 异常的 url

node.js - 更新 npm : Cannot find module 'y18n' npm ERR?

javascript - 连接激活的两个 HTML 菜单

javascript - 何时根据用户输入更新表单

javascript - JSON.stringify() 灾难性的

javascript - 两个提交按钮 - Node js Express

node.js - 如何将 Google Analytics 跟踪代码与 node-express 应用程序一起使用?

node.js - 如何在模块之间共享同一个变量?