Counters for Partials

Sometimes I like to number rows using a counter when rendering lists of things:

<% @products.each_with_index do |product, i| %>
  • <%= product.name %>
  • <% 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 :collection option:

    <%= 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:

      
  • <%= product.name %>
  • Note the use of product_counter. Rails takes the name of the partial and adds _counter to it when providing the built-in counter.

    Just be aware that unlike the counter provided by each_with_index, this counter is 1-based. I have seen some references to this counter being 1-based, but at least in the version of Rails I am using (2.3.9) the counter is 0-based.

    2 comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *