Render partial with collection has hidden counter
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
-
Hey, thanks for the tip!! I was looking for information on this and found your blog!
-
Thanks! This made my day!
-
Thanks for the post! Rails has a few 'undocumented features' that I wish were documented.
-
Thanks Paul, you're a star!
-
Thank very much for sharing hidden knowledges.
-
Seems like this is broken in Rails 2.1. The counter starts with 1 now, bug or feature?
-
Feature: http://www.ruby-forum.com/topic/154897#682999