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.
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 %>
def yield_or(name, content = nil, &block)
if content_for?(name)
content_for(name)
else
block_given? ? capture(&block) : content
end
end
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With