I\'m using Express and EJS to serve pages. I\'m using Bootstrap for the UI, specifically the navbar.
I\'d like to add an \'active\'
class to the current
In pretty much every node/express templating language I've used (ejs, kiwi, swig, jade), the answer is no. I've always just set a variable called "active" and then checked for it. As you say, it's not a great answer, though I don't know that scalability is the issue. If every url renders it's own view (or even if you have a common handler for view rendering), it shouldn't be that hard to say something like req.active = "Somepage"
. Another possibility would be to add middleware that does it for you based on the route. Something like
app.use(function(req, res, next){
req.active = req.path.split('/')[1] // [0] will be empty since routes start with '/'
next();
});
Then you just make sure any routes that have a corresponding nav component use unique paths, like
app.get('/students', ....)
app.get('/classes', ....)
app.get('/teachers', ....)
// etc.
EDIT: In response to your comment, I always throw ALL my view stuff into one object key inside req
, and usually I name the key by whatever templater I'm using. So I would probably actually use the above example to set req.ejs.active
and then do
res.render('myview', req.ejs);
This method makes it much easier to separate logic out into multiple middleware functions and not have to pass a huge anonymous object to res.render.