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

13280

Awesome little find! You got good eyes.

over 1 year ago ·
18675

Tested in Rails 3, it works also.

over 1 year ago ·
24704

Cool, thanks!

over 1 year ago ·
28893

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

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

Works in Rails 5

11 months ago ·