How to use a ternary operator to add a class to an HTML element in ejs

cdaiga picture cdaiga · Feb 1, 2017 · Viewed 10.2k times · Source

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?

Answer

Josh Crozier picture Josh Crozier · Feb 1, 2017

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>
<% } %>