6
\$\begingroup\$

I use the jQuery Calendar with an underscore template and I wanted to put <li> tags around each week. This does the trick, but it's awful.

<% _.each(days, function(day, index) { %>

    <% if ( index % 7 == 0 && index != 0) { %></li><% } %>
    <% if ( index % 7 == 0) { %><li><% } %>
    <div class="<%= day.classes %>"><%= day.day %></div>
    <% if ( _.size(days) == index + 1 ) { %></li><% } %>

<% }); %>

There must be another (elegant) way of doing this.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Interesting question,

you could definitely place the last if outside of the _.each(), this would be faster ( fewer ifs ) and cleaner.

I would also place the first <li> outside of the loop and then merge the 2 remaining if statements inside the loop.

So, something like this:

<li>
<% _.each(days, function(day, index) { %>
    <% if( index && index % 7 ) { %></li><li><% } %>
    <div class="<%= day.classes %>"><%= day.day %></div>
<% }); %>
</li>

Personally, I would forego this templating for something like this:

function fillTemplate( s ){ 
  //Replace ~ with further provided arguments  
  for( var i = 1, a = s.split('~'), s = '' ; i < arguments.length ; i++ )    
    s = s + a.shift() + arguments[i];  
  return s + a.join("");
}   

var html = '<li>';
_.each( days, function( day, index ){
  if( index && index % 7 )
    html += '</li><li>';
  html += fillTemplate('<div class="~">~</div>', day.classes, day.day );
});
html += '</li>';
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.