I am new to using ejs. I have a menu and I want to highlight the current menu item. I have tried this:
<li class=<% currentMenu == 'dashboard' ? 'active' : ''%>>
<a href= '/dashboard'>
<i class="material-icons">dashboard</i>
<span>Dashboard</span>
</a>
</li>
The value of the currentMenu is served by an express router as shown below:
app.get('/dashboard', function(req, res) {
if (isAuthorised) {
res.render('pages/index', {
title: 'Welcome | MW Tracker',
email, userName, role, menus,
currentMenu: 'dashboard'
})
} else {
res.render('pages/sign-in', {
title: 'Sign In | MW Tracker'
})
}
});
Please how am I suppose to add the class?
To set className with ternary operator add class 'null' in React, we can set the class name to an empty string. We set className to 'on' if on is true and an empty string otherwise. And we set the the on class to have background color green.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Use <% - include( 'RELATIVE/PATH/TO/FILE' ) %> to embed an EJS partial in another file. The hyphen <%- instead of just <% to tell EJS to render raw HTML. The path to the partial is relative to the current file.
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
You need to replace the <% %>
tag with the <%= %>
tag in order to output the expression value:
<li class="<%= currentMenu === 'dashboard' ? 'active' : '' %>">
<!-- -->
</li>
As the EJS documentation states, the <% %>
tags are for control-flow, no output code; whereas the <%= %>
tags output and interpolate the value into the HTML template.
For example, the if
statement below uses <% %>
tags because the statement doesn't need to be outputted into the HTML. Then inside of the condition, the variable is outputted and interpolated into the HTML template by using the <%= %>
tags: <%= currentMenu %>
.
<% if (currentMenu === 'dashboard') { %>
<span><%= currentMenu %></span>
<% } %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With