使用默认内容块生成 content_for [英] Yielding content_for with a block of default content
问题描述
我们的 Rails 项目大量使用 content_for
.但是,如果没有使用 content_for
定义任何内容,我们经常需要渲染默认内容.为了可读性和可维护性,将此默认内容放在块中是有意义的.
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.
我们在 Rails 2.3 中创建了一个辅助方法,现在我们已经为 Rails 3 重构了它(如下所示).
We made a helper method in Rails 2.3 and we've now refactored this for Rails 3 (as below).
这两个助手都工作得很好,但我想知道是否有更简洁的方法可以在 Rails 3 中实现相同的目标.
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 %>
针对 Rails 3 进行了重构:
def yield_or(name, content = nil, &block)
if content_for?(name)
content_for(name)
else
block_given? ? capture(&block) : content
end
end
推荐答案
这可以完全在视图中使用 content_for?方法.
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 %>
这篇关于使用默认内容块生成 content_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!