Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJS conditional statement change CSS

Tags:

css

node.js

ejs

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.

like image 529
shihandrana Avatar asked Mar 10 '23 06:03

shihandrana


2 Answers

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>
<% }) %>
like image 79
Krzysztof Atłasik Avatar answered Mar 25 '23 04:03

Krzysztof Atłasik


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.

like image 34
Shazam Avatar answered Mar 25 '23 04:03

Shazam