-1

New to EJS. I want to make a conditional statement basically saying if I am on this directory path, then replace this link in my nav bar.

 <%let url = window.document.URL;
            if(!url.includes('prospects/index')) {%>
<li class="nav-item">
<a class="nav-link" href="/prospects">Targeted Prospects</a>
</li>
<% } else { %>
<li class="nav-item">
<a class="nav-link" href="/prospects/new">Add Prospects</a>
</li>
<% } %>

My res.render

module.exports.index = async (req, res) => {
const prospects = await Prospect.find({});
res.render('prospects/index', { prospects })
};

I was hoping to see when I'm on my route "prospects/index" I'll see "Add Prospects" and all other routes I'll see "Targeted Prospects." Is there a way to target that route in my if statement? Thanks!

1 Answers1

0

You need to make the decision based on something accessible to the template. The values you can use in the template come from the object you pass to res.render. So that could be the request’s path, like you came up with:

res.render('prospects/index', {
    prospects,
    requestPath: req.path,
});
<% if (!requestPath.startsWith('/prospects/index')) %>

But I would prefer to let the router handle the request paths:

res.render('prospects/index', {
    prospects,
    isIndex: true,  // you might want to come up with a more descriptive name
})
<% if (!isIndex) %>

Then any non-index paths that render the same template should pass isIndex: false.

Ry-
  • 218,210
  • 55
  • 464
  • 476