Is it possible to create a function somewhere that can be called from any view in my express js mvc web app? How to declare such function in middleware to be accessed directly from a view?
So I can call this function like:
<%= getVar('my_name') %> // calling from the view
and implement return logic of the variable where the function is declared. This function may use request and response objects.
Note: 'my_name' can be anything on the view which cannot be assigned from the controller.
You can add functions to app.locals
or res.locals
just like you would add variables to it. If you want to have the request and response available in there (which, frankly, I feel bleeds a bit into what your controllers should be doing), you could create a middleware and pass those in.
From what you said in your comment, it's actually best to just set the variable that the view can use, eg:
app.use((req, res, next) => {
res.locals.value = req.session.value || 'default value';
next();
});
if you really need the function to be usable in the view, you can set it the same way, and bind the request and response to the function if needed:
function getVar(req, res, anotherArg) {
// do whatever
}
app.use((req, res, next) => {
res.locals.getVar= getVar.bind(null, req, res);
next();
});