Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yielding content_for with a block of default content

Our Rails projects make heavy use of content_for. However, we quite often need to render default content if nothing is defined using content_for. For readability and maintainability it makes sense for this default content to be in a block.

We made a helper method in Rails 2.3 and we've now refactored this for Rails 3 (as below).

Both those helpers work very well but I'm wondering if there's a more succinct way I could achieve the same thing in Rails 3.

Rails 2.3:

def yield_or(name, content = nil, &block)
  ivar = "@content_for_#{name}"

  if instance_variable_defined?(ivar)
    content = instance_variable_get(ivar)
  else
    content = block_given? ? capture(&block) : content
  end

  block_given? ? concat(content) : content
end

which is useful for doing things like this:

<%= content_for :sidebar_content do %>
    <p>Content for the sidebar</p>
<% end %>

<%= yield_or :sidebar_content do %>
    <p>Default content to render if content_for(:sidebar_content) isn't specified</p>
<% end %>

Refactored for Rails 3:

def yield_or(name, content = nil, &block)
  if content_for?(name)
    content_for(name)
  else
    block_given? ? capture(&block) : content
  end
end
like image 442
tristanm Avatar asked Sep 13 '11 23:09

tristanm


1 Answers

This can be done entirely in the view using the content_for? method.

<% if content_for?(:sidebar_content) %>
  <%= yield(:sidebar_content) %>
<% else %>
  <ul id="sidebar">
    <li>Some default content</li>
  </ul>
<% end %>
like image 104
sgrif Avatar answered Oct 27 '22 19:10

sgrif