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.
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>
<% }) %>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With