Reputation: 1656
When using Express.js/Jade, it's possible to add a function (or a variable) to res.locals and then use said function in a Jade-view like below.
In Express middleware:
res.locals.myUtilFunction = function(){ return 'Hello' };
In Jade:
- console.log(myUtilFunction());
Is it possible to achieve something similar inside of an Express route function? Like:
exports.index = function(req, res){
myUtilFunction(); //Instead of having to do res.locals.myUtilFunction() each time...
}
I've searched high and low for an answer but couldn't find one. Any help would be greatly appreciated.
Upvotes: 0
Views: 761
Reputation: 9170
You can use custom function to bind whatever you want to the request and response objects. This way you don't have to bind to the global scope.
Just put this in your initialization code before loading the router.
app.use function(req, res, next) {
req.loadWhatever = function() { ... };
return next();
}
In your routing method, you can then access req.loadWhatever
.
Upvotes: 1
Reputation: 41587
Yeah you can bind it to global although I would probably avoid making a habbit out of this
app.js
global.myFunction = function (text){
console.log(text);
}
var express = require('express');
var routes = require('./routes');
....
routes/index.js
exports.index = function(req, res){
myFunction('test');
res.render('index', { title: 'Express' });
};
Upvotes: 0