Pages

Wednesday, May 28, 2014

Counters for Partials

Sometimes I like to number rows using a counter when rendering lists of things:
<% @products.each_with_index do |product, i| %>
  <li class="product_<%= i %>"><%= product.name %></li>
<% end %>
They are handy for testing, among other things.
Of course, if the content of the block gets too big I’ll factor it out into a partial. The idiomatic Rails way of doing this is to factor the block contents out into a partial and then render it with the :collectionoption:
< %= render :partial => "product", :collection => @products %>
Which is very clean, except now where do we get our row counter? As it turns out, Rails provides one for us:
  <li class="product_<%= product_counter %>"><%= product.name %></li>
Note the use of product_counter. Rails takes the name of the partial and adds _counter to it when providing the built-in counter.

No comments:

Post a Comment