Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
cdaiga Avatar asked Feb 01 '17 18:02

cdaiga


People also ask

How do I add a class to my ternary operator?

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.

How do you write a ternary condition in HTML?

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.

How add HTML to EJS?

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.

Can you use EJS with HTML?

EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.


1 Answers

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>
<% } %>
like image 114
Josh Crozier Avatar answered Sep 28 '22 10:09

Josh Crozier