Last Updated: March 20, 2019
· 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.

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 %>
<% 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 ·

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 ·