我们的Rails项目大量使用content_for.但是,如果没有使用任何内容定义,我们经常需要呈现默认内容content_for.为了便于阅读和维护,这个默认内容在块中是有意义的.
我们在Rails 2.3中创建了一个辅助方法,现在我们已经为Rails 3重构了这个方法(如下所示).
这些助手都工作得很好,但我想知道是否有一种更简洁的方法可以在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
Run Code Online (Sandbox Code Playgroud)
这对于这样的事情很有用:
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
def yield_or(name, content = nil, &block)
if content_for?(name)
content_for(name)
else
block_given? ? capture(&block) : content
end
end
Run Code Online (Sandbox Code Playgroud)
这可以完全在视图中使用 content_for? 来完成。方法。
<% if content_for?(:sidebar_content) %>
<%= yield(:sidebar_content) %>
<% else %>
<ul id="sidebar">
<li>Some default content</li>
</ul>
<% end %>
Run Code Online (Sandbox Code Playgroud)