如果内容产生,则以其他方式呈现(Rails 3)
我已经离开Rails一段时间了,所以也许我错过了一些简单的东西。
你怎么能做到这一点:
some default content
甚至:
在第一种情况下,我正在尝试:
def yield_or(content, &block) content_for?(content) ? yield(content) : yield end
但是这会引发“无阻塞”错误。
在第二种情况:
def yield_or_render(content, template) content_for?(content) ? yield(content) : render(template) end
这在没有定义内容时有效,但只要我使用content_for覆盖默认内容,它就会抛出相同的错误。
我用这个作为起点,但它似乎只有在视图中直接使用时才有效。
谢谢!
这样的事怎么样?
<% if content_for?(:whatever) %> <%= yield(:whatever) %> <% else %> default_content_here <% end %>
这个问题的启示
试试这个:
# app/helpers/application_helper.rb def yield_or(name, content = nil, &block) if content_for?(name) content_for(name) else block_given? ? capture(&block) : content end end
所以你可以做到
<%= yield_or :something, 'default content' %>
要么
<%= yield_or :something do %> block of default content <% end %>
可以使用覆盖默认值
<%= content_for :something do %> overriding content <% end %>
我不知道你可以在没有块的情况下使用content_for(:content_tag)
,它将返回与使用yield(:content_tag)
相同的内容。
所以:
def yield_or_render(content, template) content_for?(content) ? content_for(content) : render(template) end