Multiple View paths on Node.js + Express

前端 未结 5 1600
一向
一向 2020-12-02 15:25

I\'m writing a CMS on Node.js with Express Framework. On my CMS I have several modules for users, pages, etc.

I want that each module will have his

5条回答
  •  攒了一身酷
    2020-12-02 15:53

    Here's a solution for Express 3.x. It monkey-patches express 3.x's "View" object to do the same lookup trick as @ShadowCloud's solution above. Unfortunately, the path lookup for the View object is less clean, since 3.x doesn't expose it to express -- so you have to dig into the bowels of node_modules.

    function enable_multiple_view_folders() {
        // Monkey-patch express to accept multiple paths for looking up views.
        // this path may change depending on your setup.
        var View = require("./node_modules/express/lib/view"),
            lookup_proxy = View.prototype.lookup;
    
        View.prototype.lookup = function(viewName) {
            var context, match;
            if (this.root instanceof Array) {
                for (var i = 0; i < this.root.length; i++) {
                    context = {root: this.root[i]};
                    match = lookup_proxy.call(context, viewName);
                    if (match) {
                        return match;
                    }
                }
                return null;
            }
            return lookup_proxy.call(this, viewName);
        };
    }
    
    enable_multiple_view_folders();
    

提交回复
热议问题