Reputation:
I have a navbar in my layout.hbs:
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href={{sign}}>{{issign}}</a></li>
<li><a href={{los}}>{{islog}}</a></li>
<li><a href="/">Home</a></li>
</ul>
</div>
I want to change the contents on the go, for example when the user in logged in, I want to change the login text to logout and also redirect to a different page. I am doing this through routes.
router.get('/', function(req, res, next) {
var vm = {
title: 'Join Fatty-cruxifinier',
sign: 'about',
issign : 'SIGNUP',
islog: 'LOGIN',
los: 'login'
};
res.render('signup', vm);
});
router.post('/', function(req, res, next) {
userServices.addUser(req.body, function(err){
if(err){
var vm = {
title: 'Create an account',
input: req.body,
error: err
};
delete vm.input.password;
return res.render('signup', vm);
}
res.redirect('/');
});
});
Though this seems to work, I need to add the islog
, issign
, los
and sign
variables to each and every webpage I have.
Is there a better way to do this?
Upvotes: 7
Views: 2050
Reputation: 1836
You can also use res.locals
. Anything in res.locals
will be available in the Handlebars context when the template compiles. So you might make some middleware like this:
app.use((req, res, next) => {
// get user from cookie, database, etc.
res.locals.user = user;
next();
});
If you put this middleware before your other routes, the user object will then be available to every response.
Then in your Handlebars template you simply use a conditional:
{{#if user}}
<a href=/logout>Logout</a>
{{else}}
<a href=/login>Login</a>
{{/if}}
Upvotes: 1
Reputation: 97
I did this in my project,you can use a similar approach:-
JS
var cookieuser = req.cookies.userId || '';
res.render('index', {
ID : cookieuser,
data : jsonresponse.entries
});
EJS
<ul class="dropdown-menu">
<% if(ID.length<=0) { %>
<li><a href="/Login">Login</a></li>
<% }else{ %>
<li><a href="/Logout">Logout</a></li>
<li><a href="/History">History</a></li>
<% } %>
What this does is,it stores userId as cookie,which node reads and passes to header html. EJS header checks whether Id is blank,if not means user is logged in.Basically conditionally adding li elements.
Upvotes: 0
Reputation: 1035
You can have a catch all router, and run the loggedin logic before every response.
var _ = require('lodash');
var parameters = {};
function isLoggedin(req, res, next) {
// check is the user is logged in
res.user = {
// userdata
};
next();
}
// catch all the get routes
app.get(/^(.*)$/, isLoggedin, function(req, res, next){
if (res.user) {
var _parameters = {
title: 'Join Fatty-cruxifinier',
sign: 'about',
issign : 'SIGNUP',
islog: 'LOGIN',
los: 'login'
};
} else {
var _parameters = {
title: 'Join Fatty-cruxifinier',
sign: 'about',
issign : 'SIGNUP',
islog: 'LOGIN',
los: 'login'
};
}
parameters = _.extend(parameters, _parameters);
next();
});
app.get('/account', function(req, res, next){
res.render('signup', parameters);
});
Upvotes: 0