Jim Lindley Notes

Partial Layouts

August 2nd, 2007

Partials can now have layouts. This is very useful if you need to represent small blocks of information in a repetitive but slightly varying fashion. (This example is adapted from the docs, available at: the Rails API docs for more details and code.)

View Code:

<%= render  :partial => "product", 
            :layout => "service", 
            :locals => { :product => service } %>

<%= render  :partial => "product", 
            :layout => "service", 
            :locals => { :product => item } %>

Product partial: app/views/products/_product.html.erb

<em><%= product.title %></em>

Service partial: app/views/products/_service.html.erb

<div class="product service">
  <%= yield %>
  Price: <%= item.unit_price %> per hour
</div>

Item partial: app/views/products/_item.html.erb

<div class="product item">
  <%= yield %>
  Price: <%= item.unit_price %> each
</div>

Resulting in:

<div class="product service">
  <em>Diagnostic</em>
  Price: $100.00 per hour
</div>

<div class="product item">
  <em>Oil Filter</em>
  Price: $35.00 each
</div>

Changeset #7261

UPDATE: See also Ryan Daigle, who has more in depth coverage of partial layouts.

Sorry, comments are closed for this article.