Clearing out content in content_for
In rails, multiple calls to content_for append their body's together and yield the concatenation of all the calls. Conceptually, this looks something like:
<% content_for :title do %>
Hello
<% end %>
<% content_for :title do %>
World
<% end %>
producing "Hello World" when you call
<% yield :title %>
In my current project, I was using redbox to create popup windows (see next post for details). In some cases, I wanted to have multiple popup windows on the same page. However, when I created those popups, each partial had a
content_for :title
and I was ending up with later popups having titles that contained all the words from previous titles.After a little digging, I decided I needed a version of content_for that reset the value rather than appending to it. I found some old patches for rails that changed how content_for worked, but I thought it would be cleaner to have a new method that set the content_for variable rather than patching the version in rails.
#config/initializers/set_content_for.rb
module ActionView
module Helpers
module CaptureHelper
def set_content_for(name, content = nil, &block)
ivar = "@content_for_#{name}"
instance_variable_set(ivar, nil)
content_for(name, content, &block)
end
end
end
end
by putting this in
/config/initializers
it's automatically loaded by rails at startup. You use it just like you'd use content_for<% set_content_for :title do %>
...whatever...
<end %>
but it clears out the current value of the section before setting it to the content of your new block.