Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current page in .ejs file?

I have simple Node.js web app with login/registration functionality through passport. In the nav bar I have two buttons: Login and Register. What I would like to do is when the user is on the Registration page, only display the Login button in the nav bar, when the user is on the Login Page only display the Register button in the nav bar. How can I achieve this in my header ejs file?

I tried this:

<% if (document.URL.contains("login")) { %>
    <li><a href="/login">Sign In</a></li>
<% } else { %>
    <li><a href="/register">Sign Up</a></li>
<% } %>

Problem with this is that the document variable is not defined in my ejs locals...and I don't think I can define it as a local? At least when I tried I get an error that document is not define...makes sense since this is done in the app.js file.

How can I achieve this functionality?

Thanks!

like image 542
user2573690 Avatar asked May 25 '26 01:05

user2573690


1 Answers

When you render your ejs file, provide a json object with the title.

The below would be included with your express routes:

app.route('/login')
    .get((req, res) => {
        res.render('loginTemplateEjs', { title: 'login'});
});

Then in your ejs code:

<% if (title == "login" { %>
    <li><a href="/login">Sign In</a></li>
<% } else { %>
    <li><a href="/register">Sign Up</a></li>
<% } %>
like image 95
Peter Hauge Avatar answered May 26 '26 15:05

Peter Hauge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!