Sravan SS
Sravan SS

Reputation: 79

Trouble passing data through res.locals in Express

I am trying to pass my route information to every views. I need to use req.path variable inside my index.ejs. So I tried to pass the data through res.locals, but it's not working.

My app.js

app.use((req, res, next) => {
  res.locals.path = req.path;
  next();
});

router.get('/', async (req, res) => {
  res.render('classes/index');
});

index.ejs

<% if(!path=='/'){ %>
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a href="#" class="nav-link">Log In</a>
          </li>
          <li class="nav-item">
            <a href="#" class="nav-link">Sign Up</a>
          </li>
        </ul>
<% } %>

Anyone see where I screwed up?

Upvotes: 0

Views: 2017

Answers (2)

tom
tom

Reputation: 10601

You can pass data like this:

router.get('/', async (req, res) => {
  res.render('classes/index', {path: req.path});
});

Upvotes: 0

domenikk
domenikk

Reputation: 1743

The middleware to set res.locals should come before creating router instance:

const router = require('express').Router();

app.use((req, res, next) => {
  res.locals.path = req.path;
  next();
});

router.get('/', async (req, res) => {
  res.render('classes/index');
});

app.use(router);

Upvotes: 1

Related Questions