shihandrana
shihandrana

Reputation: 220

EJS conditional statement change CSS

I have loop in EJS and I want to set css based on my data:

<% dummies.forEach(function(dummy) { %>
   <div class="panel panel-???">
   </div>
<% }) %>

my data:

var dummies = [{ 
    type: "funny",
    sure: "Yes" // this should generate panel-success
}, { 
    type: "funny", // this should generate panel-a
    sure: "No"
}, { 
    type: "happy", // this should generate panel-b
    sure: "No",
}];

So whenever sure attribute is Yes, it generates panel-success. Otherwise, it generates css based on type attribute.

Please help.

Upvotes: 5

Views: 9791

Answers (3)

saeid abdi
saeid abdi

Reputation: 55

I think this code will help : <a class="<%= 1==2 ? 'active' : '' %>" href="#"></a>

Upvotes: 2

Shazam
Shazam

Reputation: 301

Try using this code...

  <% dummies.forEach(function(dummy) { %>
    <div class="panel panel-
      <% if (dummy.sure==="yes") { %> 
        success
      <% else %>
        <%= dummy.type %>
      >
    </div>
  <% }) %>

You can just wrap your logic inside the EJS operators. It looks a little messy but it is what it is. Depending on how your server side is set up, you could also pass in parameters from the server side, instead of doing the logic on the client side.

The best way would depend on where the heavy lifting is done as far as trips to the database and any other logic going on.

Upvotes: 1

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22605

First create object like this:

<%
let cssClass = {
    funny: {
        Yes: "success",
        No: "a"
    },
    happy: {
        No: "b"
    }
} 
%>

Then you should just output value in template:

<% dummies.forEach(function(dummy) { %>
   <div class="panel panel-<%= cssClass[dummy.type][dummy.sure] %>">
   </div>
<% }) %>

Upvotes: 7

Related Questions