Repeat content in Rails with content_for

Written . Tagged Ruby, Ruby on Rails.

Just came up with a simple but useful Rails trick (though I’m likely not the first).

Say you have a long table with the same controls (buttons, pagination, whatever) both above and below it.

Doing the controls twice over is not DRY; using a helper or partial may be overkill if these controls are never reused other than these two times.

Enter content_for.

It’s commonly used to pass content such as a title or sidebar box from a template to a layout, but you can also use it within one and the same page.

Hence:

1
2
3
4
5
6
7
8
9
10
11
12
13
<% content_for :controls do %>
  <ul>
    <li>Do this</li>
    <li>Do that</li>
  </ul>
<% end %>
<%= yield :controls %>

<table>
</table>

<%= yield :controls %>

Prettier in Haml, of course:

1
2
3
4
5
6
7
8
9
10
- content_for :controls do
  %ul
    %li Do this
    %li Do that
= yield :controls

%table

= yield :controls

The effect is something like inline partials. Perfectly DRY without adding much complexity.