开发者

Render :collection wrap each item?

开发者 https://www.devze.com 2023-03-09 11:46 出处:网络
Currently I\'m using: <% @items.each do |item| %> <li class=\"list-item\"> <%= render :partial => \'/widgets/vertical_widget\',

Currently I'm using:

<% @items.each do |item| %>
  <li class="list-item">
    <%= render :partial => '/widgets/vertical_widget',
               :object => item %>
  </li>
<% end %>

to render about 20 items on a page (there's also another 20 of a different widget on the same page).

When I look at my server logs it's showing ~400ms per widget render, totaling out to ~20k ms for the page. From what I've read using :colletion instead of a loop with :object should help to improve those times however I'm not sure how I can wrap each instance of the widget in an LI if I use :collection. Not ever place 开发者_如何学运维the widget is used on the site is in a list so it doesn't make sense to include the LI in the widget code.

I could include the widget code directly in the loop rather than in a partial however I don't want to have to make code updates in multiple places.

Any other ideas to improve performance would be appreciated!


Give content_tag a try:

#some_file.html.erb

<ul>
<%= render :partial => 'widgets/vertical_widget', 
           :collection => @items, 
           :locals => { :wrap_in => :li } %>
</ul>



#/widgets/vertical_widget.html.erb

#First, render and capture the content once.
<% @rendered_content = capture do %>
  #render the item here
<% end %>

#Next, decide if the content rendered above should be wrapped in a tag or not
#If the "wrap_in" variable was passed-in and it is not nil/empty, then use that
#value for the tag; else do not wrap the content in a tag
<% if defined?(wrap_in) && !wrap_in.blank? %>
  <%= content_tag wrap_in do %>
    <%= @rendered_content %>
  <% end %>
<% else %>
    <%= @rendered_content %>
<% end %>


I realize this is a late answer but it may be useful to people with similar questions.

Zabba's answer is very good and should help as a general guideline. However, your slowness problem is probably not to do with rendering. If a single render is taking 400ms, then it's likely that you are hitting the database repeatedly within the 'vertical_widget' partial. Check your logs for what queries are going on and see if you can cache any of that using a local variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消