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

前端 未结 8 1066
半阙折子戏
半阙折子戏 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条回答
  •  Happy的楠姐
    2020-11-28 02:07

    For Express 4.0 I found that using application level variables works a little differently & Cory's answer did not work for me.

    From the docs: http://expressjs.com/en/api.html#app.locals

    I found that you could declare a global variable for the app in

    app.locals
    

    e.g

    app.locals.baseUrl = "http://www.google.com"
    

    And then in your application you can access these variables & in your express middleware you can access them in the req object as

    req.app.locals.baseUrl
    

    e.g.

    console.log(req.app.locals.baseUrl)
    //prints out http://www.google.com
    

提交回复
热议问题