David David - 1 month ago 7
jQuery Question

How to display a message when _.each(list) is empty in underscorejs?

I'm building an small web app which uses underscorejs as a template engine. I have the following code in my template:

<% _.each(tracks, function(track){ %>
<div class="title"><%= track.title %></div>
<% }) ; %>


If 'tracks' is empty, how can I display a 'No tracks available' message instead using underscorejs?

Answer

You'd just check the length, and use a condition

<% if ( tracks.length ) {
       _.each(tracks, function(track){ %>
          <div class="title"><%= track.title %></div>
       <% }); 
    } else {
       %> <div class="empty">No tracks available</div> <%
    }
%>