During my research on how to better handle globally used data I found this Question See 2. Answer
So I integrated this approach into my code basis and came up with a problem, which i would like to discuss. Hope someone can help me here.
I created a new file middleware.js
containing almost the same code as in the answer from SO, just with some small modifications:
const url = require('../db/url');
module.exports = {
render: function (view) {
return function (req, res, next) {
res.render(view);
}
},
globalLocals: function (req, res, next) {
res.locals = {
title: "My Website's Title",
pageTitle: "The Root Splash Page",
author: "Cory Gross",
description: "My app's description",
};
next();
},
index: async function (req, res, next) {
res.locals = {
index: "index2",
loggedIn: req.user ? true : false,
linkObj: await url.getAllUrl()
};
next();
}
};
In my app.js I included the file and simply told my app to use the globalLocals:
var middleware = require('./config/middleware');
app.use(middleware.globalLocals);
Afterwards without any other changes I integrated this into my ejs template
and it worked:
<h1><%= title %></h1>
Great!
After this was done I played a bit with the index
part of my middleware and also integrated this one via in my app.js
but in a different way, because I just want to make this "index" variables available for my index router for a clear seperation!!
app.use("/", middleware.index, indexRouter);
So now I was able to access the values defined in the middleware and use them in ejs. BUT I was no longer be able to access any of my globalLocals
and I don´t understand WHY?
Can someone tell me how I can keep the seperation as descibed above and access both objects in my ejs template?