Last Updated: April 10, 2023
·
16.65K
· lordkeper

Render partial with collection has "hidden" index

Wen rendering a partial with a collection, sometimes is necessary an index to apply some css class or other stuff.

I recently found an "undocumented" feature, inside partial exist "#{partial_name}_counter" with the iteration index. https://github.com/rails/rails/blob/4-0-stable/actionpack/lib/action_view/renderer/partial_renderer.rb#L480

For example, usual post rendering:

<%= render partial: 'post', collection: @posts %>

Inside _post.html.erb we can do something like this:

<% index = post_counter + 1 %>
<%= content_tag :div, class: "post-#{index}" do %>
  content...
<% end -%>

I only try it in Rails 4, I don't know if it works in previous versions.

6 Responses
Add your response

Awesome little find! You got good eyes.

over 1 year ago ·

Tested in Rails 3, it works also.

over 1 year ago ·

Cool, thanks!

over 1 year ago ·

Your render line can be shortened:

<%= render @posts %>

Rails understands that @posts is a collection of Post models and will render each with the _post.html.erb template.

over 1 year ago ·

Typo:
The variable name is not #{partial_name}_counter, in fact it is #{variable_name}_counter
<%= render partial: "post", collection: @posts %> makes the counter post_counter.
<%= render partial: "my_partial", collection: @items, as: :item %> makes the counter item_counter.

over 1 year ago ·

Works in Rails 5

over 1 year ago ·