简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM