How to Handle Global Data in ExpressJS

前端 未结 5 1337
深忆病人
深忆病人 2021-01-21 19:22

I am trying to build an express.js app and I want to pass some data to my main layout. For example, a list of navigation links that I use on every page. I know how to pass data

相关标签:
5条回答
  • 2021-01-21 19:27

    Why are you not just using global state?

    const navbarItems = [{ pageTitle: 'Home' }]
    
    app.get('/', (req, res) => {
     res.render('index', navbarItems);
    }
    
    0 讨论(0)
  • 2021-01-21 19:46

    A better solution instead of using app.locals will be to set a middleware that runs before each route.

    app.use((req,res,next) => {
      res.locals.navLinks = [ 
        // array data
      ];
      next()
    });
    

    Will run before any HTTP request and will set the navLinks before every route.

    this will cause the navLinks to be valid only for the request lifetime and won't polute app.locals. (which will persist throughout the life of the application).

    0 讨论(0)
  • 2021-01-21 19:48

    Here you can include file of header & footer inside your each ejs file

    <%- include('<path>/header.ejs') %>
    <%- include('<path>/footer.ejs') %>
    

    This is for ejs view engine

    app.set("view engine", "ejs");
    
    0 讨论(0)
  • 2021-01-21 19:48

    I ended up using app.locals like this:

    // app.js
    app.locals.navLinks = [ 
      // array data
    ]
    

    I can then use it in my views (including my layout views) as follows:

    // views/layouts/main.html
    {{#each navLinks}}
      <a href="{{ url }}">{{title}}</a>
    {{/each}}
    
    0 讨论(0)
  • 2021-01-21 19:52

    You don't send vars to the layout in any special way: whatever you send to the template is accessible in the layout.

    You have a few options here:

    • you populate those vars in every request handler, meaning you'll have to duplicate the call to the function that populates those
    • you use some global variables as @garritfra suggested, meaning those vars will be application specific and not request-specific (ie: the same for all the users)
    • you create an express middleware where you'll populate those variables and apply it to the routes. I'd say this is the way to go, because that middleware can also use the global variables and can also populate the variables with request-specific info.
    0 讨论(0)
提交回复
热议问题