Render partial with collection has hidden counter

written by paul on July 20th, 2007 @ 12:50 AM

When rendering a partial with a collection, it can be useful to know the index of the item currently being rendered. It turns out that rails provides this with an undocumented counter.

For example, say we want to render a collection of people who won a contest. We might have a template line like this:


<%= render :partial => "person", :collection => @winners %>

The person partial might look like:


<div>Name: <%= person.name %></div>

Now, let’s say we want to add the person’s rank along with his/her name. Rails provides a local variable called ”#{partial_name}_counter” to provide the index of the currently rendered item in the collection. In our case, the variable is called person_counter. The counter starts at 0, so we’ll add 1 to it for a human readable ranking.

Now, our person partial looks like:


<div>
  Rank: <%= person_counter + 1 %> 
  Name: <%= person.name %>
</div>

And the output is:

Rank: 1 Name: Peter
Rank: 2 Name: Paul
Rank: 3 Name: Mary

Update (6/20/08): Jan points out in the comments that the counter now starts at 1 in Rails 2.1.

Comments

  • John on 30 Jul 08:42

    Hey, thanks for the tip!! I was looking for information on this and found your blog!
  • Joakim on 09 Nov 00:33

    Thanks! This made my day!
  • Alastair on 31 Dec 17:10

    Thanks for the post! Rails has a few 'undocumented features' that I wish were documented.
  • JN2 on 08 Jan 08:14

    Thanks Paul, you're a star!
  • Fernando on 28 Apr 22:15

    Thank very much for sharing hidden knowledges.
  • Jan on 02 Jun 12:28

    Seems like this is broken in Rails 2.1. The counter starts with 1 now, bug or feature?
  • Jan on 02 Jun 13:29

    Feature: http://www.ruby-forum.com/topic/154897#682999

Post a comment

Options:

Size

Colors