Question: EJS conditional statement change CSS

Question

EJS conditional statement change CSS

Answers 2
Added at 2017-01-01 23:01
Tags
Question

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.

Answers
nr: #1 dodano: 2017-01-01 23:01

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>
<% }) %>
nr: #2 dodano: 2017-01-02 07:01

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.

Source Show
◀ Wstecz