Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

javascript - Finding current url inside EJS view when using express

I'm using Express and EJS to serve pages. I'm using Bootstrap for the UI, specifically the navbar.

I'd like to add an 'active' class to the current page's <li> item, to show the current page. However, I cannot find how to get the URL from within the EJS code rendering the page.

I found 2 workarounds: I used included passing the page name as a parameter in the route's res.render('myview', {pageName: 'myView'}); - which is not scalable and may cause issues.

The other way, was to use jQuery on the client side to add the 'active' class to the item upon page ready - but that means including this piece of script on every view + some useless client side cycles.

Having used several server side rendering languages before, I feel like I'm missing something. And the online EJS documentation is not that great.

Is there any way to find my current path/url from the EJS code?

Update: I took the top 2 suggestions, and passed the view name as a parameter to the view. I really liked @tandrewnichols' idea to calculate it automatically, but ultimately, it was easier to just copy-paste strings :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I know, you can't do what you're asking for unless you modify EJS internally. However, a less bothersome solution would be to pass the URL property of the request on each page invocation, rather than define it per route.

app.get('/url', function (req, res) {
  res.render('view', {
    page: req.url,
    nav: {
      'Page 1': '/page1',
      'Page 2': '/page2',
      'Page 3': '/page3'
    }
  });
});

If you only wanted to get the first part of the URL and match it, then you could just call split('/') on req.url. You could then put a loop inside your template file to create the list for your navigation bar.

<% nav.forEach(function(title) { %>
  <% if (nav[title] == page) { %>
    <li class="active">This part of the navigation bar is active.</li>
  <% } else { %>
    <li>This part of the navigation bar is normal.</li>
  <% } %>
<% }) %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...