content_for(name, &block) public

Content_for will store the given block in an instance variable for later use in another template or in the layout.

The name of the instance variable is content_for_<name> to stay consistent with @content_for_layout which is used by ActionView's layouts


  <% content_for("header") do %>
    alert('hello world')
  <% end %>

You can use @content_for_header anywhere in your templates.

NOTE: Beware that content_for is ignored in caches. So you shouldn’t use it for elements that are going to be fragment cached.

Show source
Register or log in to add new notes.
November 30, 2009
2 thanks

Clearing out previous values from content_for

By default, content_for :thing appends whatever you put in your block to the previous value of :thing. In some cases, you’d like to clear out :thing rather than append to it.

I just posted a way to do this on my blog:

I add a new method set_content_for that works just like content_for, but clears out :thing first. It doesn’t touch how content_for works, so it shouldn’t cause any problems anywhere else in your app.

November 26, 2009
0 thanks

How to check if a Yield has content?

How do I do this without actually calling the yield?

- if yield :footer
  = yield :footer
- else
  = render "layouts/footer_big"

(Note: HAML Syntax) Thanks.

July 10, 2012
0 thanks

Checking content_for

@tordans You asked your question 3 years ago, but in any case, should anyone have that same issue, you can manage that with:

- unless content_for(:footer).blank?
- else
  == render "layouts/footer_big"

content_for(:x) defaults to an empty string, that’s why you need to check for blank? not nil?.

February 22, 2013
0 thanks

Checking content_for

There’s a much simpler way to check if content exists or not, and it’s been provided as example in docs since 05.2010:

module StorageHelper
  def stored_content
    content_for(:storage) || "Your storage is empty"

But this behavior was broken with SafeBuffer. You’ll be able to use it again when this issue ( will be fixed and merged with master.