How to Handle Global Data in ExpressJS

坚强是说给别人听的谎言 提交于 2020-07-31 03:18:07

问题


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 to an individual view -- for example:

app.get('/', (req, res) => {
 res.render('index', { pageTitle: 'Home' });
}

But what if I want to pass data to my main layout (as opposed to an individual view). For example, let's say a list of links that I put in a header navbar that appears on each and every page.

How do I pass that data into my main layout?

Thanks.


回答1:


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).




回答2:


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");



回答3:


Why are you not just using global state?

const navbarItems = [{ pageTitle: 'Home' }]

app.get('/', (req, res) => {
 res.render('index', navbarItems);
}



回答4:


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.



回答5:


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}}


来源:https://stackoverflow.com/questions/62951043/how-to-handle-global-data-in-expressjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!