I have a loop that renders a partial
1000.times do |i|
render partial: \'test\', locals: {i: i}
end
this is really slow, up to 0.1 ms for for
You could add a helper method and use content_tag
. This accomplishes your goal of having a method work as a partial.
def my_partial(i)
content_tag(:div, i, class: 'iterator')
end
Using helper methods with content_tag
probably isn't a good solution if you have a lot of content in your partial, for readability's sake.
An alternative recommendation: Instead of rendering the same partial multiple times within a loop, you could render a single partial that includes a loop. If you needed to reuse the partial for only one object, you could just pass the object as an array.
Here's a more real-world example:
# index.html.erb
<%= render partial: 'dogs', locals: {dogs: @dogs} %>
# show.html.erb
<%= render partial: 'dogs', locals: {dogs: [@dog]} %>
# _dogs.html.erb
<% dogs.each do |dog| %>
<%= dog.name %>
<% end %>