Teaching Newbies since 2014

kauress

  • Home
  • Javascript ❤
    • JavaScript
    • Node.js
  • WebDev Tuts
  • screencasts
  • Resources
  • VR & AR
  • Contact
  • Github
  • Twitter
  • YouTube
  • RSS
  • C++
You are here: Home / Node Newbs / #nodebeginner / Conditionally rendering EJS template with res.locals in express.js

August 12, 2019 by: Kauress

Conditionally rendering EJS template with res.locals in express.js

This snippet is to conditionally render navbar items based on whether a user is logged in OR not.  So toggle the ‘Login’ button to ‘Logout’ if the user is already logged in and vice versa. I admit it took more time that I had anticipated. Primarily because in the beginning I insisted on using a global variable in express to manage the user’s ‘isAuthenticated’  state so as to pass values to an EJS  partial. So  I declared and initialized with the keywords ‘global’ and then global.varName = boolean. And then in the  routes I changed the value of the ‘isLoggedIn’ global variable to true/false depending on whether the user was logged in or not. Also I was leaving res.locals alone so that others could extend the functionality if need be themselves.

Then I deployed to Heroku and broke the app. So I finally decided to just use res.locals which I had looked at initially. Here it is with
[code]

In app.js

//sessions
app.use(session({
secret: require(“./bin/config”).sessionSecret,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 300000
}
}));

// middleware to make ‘user’ available to all templates
app.use(function (req, res, next) {
if(req.session.userId !== undefined){
res.locals.loggedIn = req.user;
} else{
res.locals.loggedIn = null;
}
next()
})

 
[/code]

[code]
In navbar.ejs

TROPICA

<% if (locals.user === null) { %>
Home (current)
Features
Pricing
Login

<% } else { %>
Home (current)
Features
Pricing
Dashboard
Logout
<% } %>



 [/code]

Simply Auth now on heroku!
Tricks learned this month

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2021 ·Kauress