Performance: Partial templates
Partial templates affect page load speed by controlling how much HTML is rendered and reused, impacting server response time and browser rendering.
<%= render 'items', items: @items %> <!-- Render a single partial that loops internally --><%= render partial: 'item', collection: @items %>| Pattern | DOM Operations | Render Calls | Paint Cost | Verdict |
|---|---|---|---|---|
| Many small partial renders | N partial renders | N render calls | Higher paint delay due to slower HTML delivery | [X] Bad |
| Single partial with internal loop | 1 partial render | 1 render call | Faster paint due to quicker HTML delivery | [OK] Good |
_menu.html.erb in a Rails view?render 'partial_name' to include partials, omitting the underscore and file extension.<%= render 'menu' %> to render _menu.html.erb.<%= render partial: 'product', collection: @products, as: :item %>
_product.html.erb partial for each item?render partial: 'name', collection: ..., as: :var, each element is passed as var inside the partial.as: :item means inside _product.html.erb each element is accessible as item.<%= render 'user', user: @user %>
_user.html.erb and expects a local variable user.render 'user', user: @user._user.html.erb automatically._comment.html.erb. Each comment should be passed as comment local variable. Which is the best way to do this in Rails?render partial: 'comment', collection: @comments, Rails passes each element as comment by default (partial name without underscore).<%= render 'comment', comments: @comments %> passes the whole array as a single local, not each comment. <%= render partial: 'comment', collection: @comments, as: :comments %> passes each as comments (plural). <%= render partial: 'comment', locals: { comment: @comments } %> passes the entire array as one variable, not individual comments.Pass the test and this pattern moves unknown