David David - 1 year ago 71
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 Source

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> <%
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download