Reputation: 37
I am currently trying to develop a partial templating file for a navbar using ejs, however I am struggling to add additional classes to an element which already has classes added to it.
I have tried 2 methods of adding the additional class, this is the first one:
<li class='navbar-item'<% if (pageTitle === 'Home') { %> class="active" <% } %>> <a href="/home">Home</a></li>
However this did not work so I decided to try embedding the EJS inside the class attribute, as follows
<li class="nav-item <% if (pageTitle === 'Home') { %> active <% } %>">
This also did not work, I have ensured that pageTitle is being served correctly as it is used elsewhere within the webpage and works fine.
I am not sure as to what the next stage is, I have considered using an additional JS file but that seems counter productive as I already have the ability to embed the JS inside the HTML.
Any help is appreciated, thanks in advance.
Upvotes: 2
Views: 2912
Reputation: 3186
You can make your life easier with a Conditional operator like this
<li class="<%= pageTitle == 'Home' ? 'navbar-item active' : 'navbar-item' %>"
Upvotes: 7
Reputation: 37
Using an if else statement, I have managed to develop an alternative solution to my own question. I came to this conclusion after discussing with a classmate who stated a relatively easy solution to this.
<li <% if (pageTitle == 'Home') { %> class='navbar-item active'<% } else { %> class = 'navbar-item' <% } %>>
This is not exactly as I wished for it to work but works effectively none the less.
Upvotes: 0
Reputation: 303
I think the issue might be in the comparison. As a first check, in your second version try both '==' and also '!='. If '!=' gives you the 'current' class, you know that the logic in general is fine. For more details, and an even better approach on how to compare Strings here, please have a look here: How could I compare two string in Jsp?
Upvotes: 0