I've created an external file that's handling the dynamic helpers, which includes a bunch of functions that I want to be able to use from all my views.
In on of the functions I'm running a query and fetch tags from the database, which I want to use in my layout.jade file (that all other views is using). In the console, all seems ok. The query returns the tags object, but by some strange reason I can't return the object to the view, which gives me an error message telling me that "tags" is undefined".
This is the code in my file dynamicHelpers.js:
exports.tags = function(req, res){
var environment = require('../environment');
var service = require('../service');
service.init(environment);
var model = service.useModel('tag');
var query = model.Tag.find({});
query.exec(function (err, tags) {
if (err) {
console.log(err);
// do something
}
console.log(tags);
return tags;
});
}
in layout.jade i'm getting the object in this way (this shows undefined):
p
#{tags}
What I actually want to do is to loop through all the tags with 'each'. So a follow-up issue would be if this is allowed and possible (if 'tags' were not undefined)?
ul.tags
each tag in #{tags}
a(href='/tag/' + tag._id.toHexString())
li.tag= tag.name
UPDATE: I've tried @Linus G Thiel's solution (see below), but can't get it to work (res.tags gets undefined). With console.log(tags) in the middleware, it prints out the object. However, in the dynamicHelper function below it gets undefined. Seems like res.tags doesn't get passed to the dynamicHelper by some reason.
dynamicHelpers.js:
exports.tags = function(req, res) {
console.log(req.tags); <--- undefined
return req.tags;
};
configuration.js:
module.exports = function(app, express, next){
app.configure(function() {
// lots of more app.use functions (eg. express.cookieParser());)
// ...
app.use(function(req, res, next) {
var environment = require('./environment');
var service = require('./service');
service.init(environment);
var model = service.useModel('tag');
var query = model.Tag.find({});
query.exec(function (err, tags) {
if (err) {
return next(err);
}
req.tags = tags;
next();
console.log(req.tags); <--- works fine
});
});
});
};