Site icon Teaching Newbies since 2014

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

Exit mobile version