简体   繁体   中英

Underscore.js adding if/else to each function

I am currently using a clndr.js calendar and underscore.js templates.

Looking for some help implementing an if/else statement within the underscore <% _.each function.

<div class="days">
    <% _.each(days, function(day) { %>
    <div class="event <%= day.classes %>" id="<%= day.id %>">
        <div class="number"><%= day.day %></div>
        <% _.each(day.events, function(event){ %>
             <div class="event <%= event.val %>"></div>
        <% }) %>
    </div>
    <% }); %>
</div>

At the moment <div class="event <%= event.val %>"></div> is shown for each day in the calendar where an event exists, which is great. However, I also want to add a div for days when an event does not exist:

<div class="days">
    <% _.each(days, function(day) { %>
    <div class="<%= day.classes %>" id="<%= day.id %>">
        <div class="number"><%= day.day %></div>
        <% _.each(day.events, function(event){ %>

             # if the event exists, show this div
             <div class="event <%= event.val %>"></div>

             # else if the event does not exist, show this div:
             <div class="event none"></div>
        <% }) %>
    </div>
    <% }); %>
</div>

The fact that it's within a each callback doesn't change a thing. Underscore's template can use JavaScript directly.

<% if (event && event.val) { %>
    <div class="event <%= event.val %>"></div>
<% } else { %>
    <div class="event none"></div>
<% } %>

Or since your example is trivial, the following would be enough.

<div class="event <%= event.val || 'none' %>"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM