Yielding content_for with a block of default content

六眼飞鱼酱① 提交于 2020-01-11 02:39:31

问题


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

回答1:


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 %>


来源:https://stackoverflow.com/questions/7409646/yielding-content-for-with-a-block-of-default-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!