BEST_PRACTICES /
content_for

← Back

Limit usage of content_for helper. The use of content_for is the same as setting an instance variable plus capture.

<% content_for :foo do %>
  Hello
<% end %>

Is effectively the same as

<% @foo_content = capture do %>
  Hello
<% end %>

See documentation on avoiding instance variables in templates.

Common Anti-patterns

Using content_for within the same template to capture data.

Instead, just use capture.

<!-- bad -->
<% content_for :page do %>
  Hello
<% end %>

<% if foo? %>
  <div class="container">
    <%= yield :page %>
  </div>
<% else %>
  <%= yield :page %>
<% end %>

Simply capture and use a local variable since the result is only needed in this template.

<!-- good -->
<% page = capture do %>
  Hello
<% end %>

<% if foo? %>
  <div class="container">
    <%= page %>
  </div>
<% else %>
  <%= page %>
<% end %>

Using content_for to pass content to a subtemplate.

Instead, render layout: with a block.

<!-- bad -->
<% content_for :page do %>
  Hello
<% end %>
<%= render partial: "page" %>


<!-- _page.html.erb -->
<div class="container">
  <%= yield :page %>
</div>

Pass the content in a block directly to the render function.

<!-- good -->
<%= render layout: "page" do %>
  Hello
<% end %>


<!-- _page.html.erb -->
<div class="container">
  <%= yield %>
</div>