Any idea , i want to add an express middleware to check for a cookie ( theme=dark ) and if exists adding the class … knowing that the middleware is in a separate file. I know how to create the middleware but how to communicate between the middleware and the ejs view?
CodePudding user response:
Views will look in a couple couple places for data. One such place is res.locals
(see doc here). So, since every middleware gets passed the res
object, you can set some data in res.locals
in the middleware and that will automatically be passed to the template.
For example:
app.use((res, req, next) => {
res.locals.appName = "My App";
next();
});
Then, you template could refer to the appName
variable:
<%=appName%>
Otherwise, you could pass the data from your middleware to the actual route that renders the template by creating your own property on the res
or req
object and the route handler can grab the data from there and pass it as the data argument with res.render(templateName, dataObj)
.