Rails Partial Templates

A partial template is really just like any other template but can take parameters. These can also be called ‘partials’.

If you pass in an instance of one model, it will be rendered once; If you pass into it a collection of records of model instances, it will be rendered multiple times.

A partial template can be called/rendered from a controller or another template. Also partial templates can call/render other partial templates.

If you are doing too much in your regular non-partial template, move it to a Partial Template, also to keep your code DRY.

For example, in your regular non-partial template, for new and edit, there is usually some duplication. Move that duplicated code into a partial template.

Rails will detect that only one record is passed to the partial _game.html.erb.

In index.html.erb for example:

<% title "Game" %>
<%= render :partial => @game %>

OR:

<% title "Game" %>
<%= render :partial => 'game', :object => @game %>

In the _game.html.erb partial, for example:

<%= game.name %>
<%= game.type %>

Rails will detect that multiple records are passed to the partial _game.html.erb.

In index.html.erb for example:

<% title "Games" %>
<%= render :partial => @games %>

OR:

<% title "Games" %>
<%= render :partial => 'game', :collection => @games %>

In the _game.html.erb partial, for example:

<%= game.name %>
<%= game.type %>

Sometimes you want to render a partial template that’s not in the default location. For instance, this partial views/stores/_fields.html.erb is associated with the ‘stores’ view not ‘products’ but it can still be rendered.

Imagine the following code is located in views/products/new.html.erb and you want to display two separate forms after each other both on the same page. Each store has many products. :locals allows you to pass variables to your partial template.

<% form_for(@store) do |f| %>
  <%= render :partial => '/stores/fields', :locals => { :f => f } %>
    <%= f.submit "Create" %>
<% end %>

<% form_for(@product) do |f| %>
  <%= render :partial => '/products/fields', :locals => { :f => f } %>
    <%= f.submit "Create" %>
<% end %>
VN:F [1.9.22_1171]
Rating: 3.9/5 (14 votes cast)
VN:F [1.9.22_1171]
Rating: +5 (from 7 votes)
Rails Partial Templates, 3.9 out of 5 based on 14 ratings
Facebook Twitter Email

One Comment to “Rails Partial Templates”

  1. lenghorne 16 February 2013 at 3:34 pm #

    How do you use the variables in the partial templates itself. if i have
    ‘house’, :locals => { :height => 100 } %>

    how do I access the height variable from the file _house.html.erb? Would this work:
    The height of the house is

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

Leave a Reply