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.
Written by Victor Ortiz
Related protips
6 Responses
Awesome little find! You got good eyes.
Tested in Rails 3, it works also.
Cool, thanks!
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.
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
.
Works in Rails 5