Home > other >  EJS if else statment, array items
EJS if else statment, array items

Time:01-23

Im trying to render some API data using express (REST) and EJS (template engine) depending on which value "status" has. If any item in the array contains a status which is not "CLOSED" it should proceed and show those and if every item in the array has the status value set to "CLOSED" it should render a message saying "not found / no active cases"

<% for (var i=0, n=array.length; i < n;   i){ %>
<% if (array[i].status !== "CLOSED") { %>
     
     // This works as intendend and only renders array items without the status set to closed  
     <div><% array[i].status %> </div> 

<% } else { %>
    
     // This will however render this message the in the amount of array items that exists.
     <div>Not found / no active cases </div>
<% } %>

How can I break out of the loop somehow and only display the message once?

The following has been tried and it works, sort of, however the message keeps looping.

<% for (var i=0, n=array.length; i < n;   i){ %>
<% if (array[i].status !== "CLOSED") { %>
     
     // This works as intendend and only renders array items without the status set to closed  
     <div><% array[i].status %> </div> 

<% } else { %>
    
     // This will however render this message the in the amount of array items that exists.
     <div>Not found / no active cases </div>
<% } %>

I have also tried this, this yields the same result as the above.

<% for (var i=0, n=array.length; i < n;   i){ %>
<% if (array[i].status !== "CLOSED") { %>
     
     <div><% array[i].status %> </div> 

<% } else if(array[i].status === "CLOSED") { %>
     <div>Not found / no active cases </div>
  <% } %>
<% } %>

CodePudding user response:

You could filter all the elements which don't have status CLOSED, and if there are any, render them, else, show the message:

<% const notClosed = array.filter(el=> el.status !== 'CLOSED'); %>

<% if(notClosed.length > 0) {%>

    <% notClosed.forEach(el=>{ %>

            <div><%= el.status; %> </div>

    <% }); %>

<% } else { %>

     <div>Not found / no active cases </div>

<% } %>
  • Related