Ruby on Rails Partials


Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.

To create a partial, create a new file that begins with an underscore: _form.html.erb

To render a partial as part of a view, use the render method within the view: <%= render "form" %>

  • Note, the underscore is left out when rendering
  • A partial has to be rendered using its path if located in a different folder

To pass a variable into the partial as a local variable, use this notation:

<%= render :partial => 'form', locals: { post: @post } %>

Partials are also useful when you need to reuse exactly the same code (DRY philosophy).

For example, to reuse <head> code, create a partial named _html_header.html.erb, enter your <head> code to be reused, and render the partial whenever needed by: <%= render 'html_header' %>.

Object Partials

Objects that respond to to_partial_path can also be rendered, as in <%= render @post %>. By default, for ActiveRecord models, this will be something like posts/post, so by actually rendering @post, the file views/posts/_post.html.erb will be rendered.

A local named post will be automatically assigned. In the end, <%= render @post %> is a short hand for <%= render 'posts/post', post: @post %>.

Collections of objects that respond to to_partial_path can also be provided, such as <%= render @posts %>. Each item will be rendered consecutively.

Global Partials

To create a global partial that can be used anywhere without referencing its exact path, the partial has to be located in the views/application path. The previous example has been modified below to illustrate this feature.

For example, this is a path to a global partial app/views/application/_html_header.html.erb:

To render this global partial anywhere, use <%= render 'html_header' %>