content_for
content_for(name, content = nil, &block)
public
Calling content_for stores the block of markup for later use. Subsequently, you can make calls to it by name with yield in another template or in the layout.
Example:
<% content_for("header") do %> alert('hello world') <% end %>
You can use yield :header anywhere in your templates.
<%= yield :header %>
NOTE: Beware that content_for is ignored in caches. So you shouldn’t use it for elements that are going to be fragment cached.
The deprecated way of accessing a content_for block was to use a instance variable named @@content_for_#{name_of_the_content_block}@. So <%= content_for('footer') %> would be avaiable as <%= @content_for_footer %>. The preferred notation now is <%= yield :footer %>.
Check content_for content
There is a content_for? method in Rails wherewith you can check the content. http://github.com/rails/rails/commit/9cb8c812f2a23ab5653a7888740a014a02c97c18#diff-1
But it’s not in the last stable version (2.3.5) http://github.com/rails/rails/blob/v2.3.5/actionpack/lib/action_view/helpers/capture_helper.rb
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.
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: http://stevechanin.blogspot.com/2009/11/clearing-out-content-in-contentfor.html
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.

