Kaushik Makwana
Kaushik Makwana

Reputation: 2576

How can I access session data in an EJS template with a node.js backend?

I have created a dynamic menubar based on the user's role. On the server side, when the user is logged in I am storing all their allowed pages in their session.

Now, I have 15 templates. I have included menubar.html file on each and every page. I want to use session data in menubar.html without having to pass it explicitly each time.

I have tried the following code:

app.get('/home',function(req,res)){
  res.render('home',{menu : req.session.menubar})
}
app.get('/contact',function(req,res)){
  res.render('contact',{menu : req.session.menubar})
}    

In above code, I need to pass session data on every page. If I have 50 html templates, it's not efficient to pass the session in each and every route.

What is the best approach to handle this?

Upvotes: 2

Views: 7690

Answers (3)

shahriarpshuvo
shahriarpshuvo

Reputation: 464

In order to get it on every templates, you need to store the session on database collections first. You use connect-mongo package for that. From the docs:

const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

app.use(session({
    secret: 'foo',
    store: new MongoStore(options)
}));

Upvotes: 0

rotarydial
rotarydial

Reputation: 2581

  1. Are you including your HTML files as shown in this answer?

  2. Assuming you are using express-session, you may also need to set up middleware to assign session information to the response (res), as shown in this answer.

app.js:

app.use(session({
  secret: "sosecret",
  saveUninitialized: false,
  resave: false
}));

// middleware to make 'user' available to all templates
app.use(function(req, res, next) {
  res.locals.user = req.session.user;
  next();
});

Then try referring to res.locals.user rather than the request object.

Upvotes: 5

Deep Kakkar
Deep Kakkar

Reputation: 6297

Since EJS is based on escaping to JavaScript, rendering lists can be done using the loop constructs in the language.

To display the value of array on your ejs template, you can use the following code:

<ul class="menubar">
  <% for(var i=0; i < menu.length; i++) { %>
     <li class="menu-title">
        <%= menu[i] %>
     </li>
  <% } %>

Upvotes: 0

Related Questions