I'm learning node js and using pug-template engine to create a simple login/admin page for hotel bookings.
When a user is logged in the index page should be different from a not logged in user.
Should i do a condition in my template or a condition in my home route to render a index_logged or index_not_logged?
Currently doing
app.get('/', (req, res) => {
User.find({}, function(err, users) {
if(err) {
console.log(err);
} else {
res.render("index", {
title: "Willkommen",
users: users
});
}
});
});
and in my index.pug
extends layout
block content
if user
h1 #{title}
ul.list-group
each user, i in users
li.list-group-item
a(href="/users/"+user._id)= user.name
else
.jumbotron
h1 #{title}
a(href="/users/login").btn.btn-primary Anmelden
I'm using a global user variable at the moment.
If your public / is very different from the logged in /, then render two separate pug views, example:
app.get('/', (req, res) => {
User.find({}, function(err, users) {
if (err) {
console.log(err);
res.render("public_index");
} else {
res.render("index", {
title: "Willkommen",
users: users
});
}
});
});
But if the two pages are very similar with a few certain parts different, then render the same view but use if user (theoretically you can have this in as many places as you like in the view file) to display the relevant content accordingly, like what you have in the index.pug in your question. Your app logic should be:
app.get('/', (req, res) => {
User.find({}, function(err, users) {
let Users = undefined;
if (err) {
console.log(err);
} else {
Users = users
}
res.render("index", { title: "Wilkommen", users: Users });
});
});