EJS conditional rendering not working as expected

69 Views Asked by At

I'm trying to implement this code but it doesn't work as expected. The problem is explained below.

<% if (Object.keys(notes).length !== 0) { %>
<p class="card-text w-100" id="bookShelf">
   <div class="inline-block">
   <% notes.forEach(note => { %>
      <div class="card ml-2" style="width: 18rem;">
         <div class="card-body">
            <h5 class="card-title"><%= note.title %> </h5>
            <p class="card-text"><%= note.body %> </p>
         </div>
      </div>
   <% }); %>
   </div> 
</p>
<% } else { %>
<p class="card-text w-100" id="bookShelf" aria-placeholder="Add some notes...">
   You have not added any notes
</p>
<% } %> 

In the above code, the 'notes' object is served from the back-end and is not empty. When rendering this ejs code I get the output in such a way that the last 'card-text' paragraph element still get served to the front-end with no element. And first 'card-text' paragraph element gets displayed separately instead of enclosing the div element containing notes. In an ideal case, it is expected to display either one of the paragraph elements but not both.

Please refer to the screenshots attached for a better understanding of the problem. I already have spent too much time on this and still couldn't figure out the issue unless it is bug of some type. Any suggestion or help however small will be appreciated.

Inspect tools snap webpage sc1 webpage sc2

EDIT: Please note that it works as expected when 'notes' object is empty i.e. only the last paragraph element is displayed.

0

There are 0 best solutions below