How to create global variables accessible in all views using Express / Node.JS?

前端 未结 8 1060
半阙折子戏
半阙折子戏 2020-11-28 01:53

Ok, so I have built a blog using Jekyll and you can define variables in a file _config.yml which are accessible in all of the templates/layouts. I am currently

8条回答
  •  粉色の甜心
    2020-11-28 02:20

    You can do this by adding them to the locals object in a general middleware.

    app.use(function (req, res, next) {
       res.locals = {
         siteTitle: "My Website's Title",
         pageTitle: "The Home Page",
         author: "Cory Gross",
         description: "My app's description",
       };
       next();
    });
    

    Locals is also a function which will extend the locals object rather than overwriting it. So the following works as well

    res.locals({
      siteTitle: "My Website's Title",
      pageTitle: "The Home Page",
      author: "Cory Gross",
      description: "My app's description",
    });
    

    Full example

    var app = express();
    
    var middleware = {
    
        render: function (view) {
            return function (req, res, next) {
                res.render(view);
            }
        },
    
        globalLocals: function (req, res, next) {
            res.locals({ 
                siteTitle: "My Website's Title",
                pageTitle: "The Root Splash Page",
                author: "Cory Gross",
                description: "My app's description",
            });
            next();
        },
    
        index: function (req, res, next) {
            res.locals({
                indexSpecificData: someData
            });
            next();
        }
    
    };
    
    
    app.use(middleware.globalLocals);
    app.get('/', middleware.index, middleware.render('home'));
    app.get('/products', middleware.products, middleware.render('products'));
    

    I also added a generic render middleware. This way you don't have to add res.render to each route which means you have better code reuse. Once you go down the reusable middleware route you'll notice you will have lots of building blocks which will speed up development tremendously.

提交回复
热议问题