Don't show div surrounding a yield if nothing calls it
I have this snippet in a layout:
<div class="yui-g" style="min-width: 760px">
<!-- top row -->
<%= yield :top_row %>
</div>
If nothing calls content_for :top_row
then i'm left with a styled, empty rectangle on the page. The right thing to do would be restyle the layout (and the whole site tbh) but that's not an option right now (le开发者_如何学Gogacy debt and more pressing requirements). Is there a way to wrap the div in some code that checks if the yield is actually yielding to anything, and to not render it if so?
cheers, max
EDIT - this is a rails 2.2.2 project btw.
EDIT 2
@arnep suggested the following, which works:
<% content = yield :top_row %>
<% unless content.blank? %>
<div class="yui-g" style="min-width: 760px">
<%= content %>
</div>
<% end %>
What i'd like to do next is to wrap that up in a helper which i can use like so:
<% yield_if(:top_row) do |content| %>
<div class="yui-g" style="min-width: 760px">
<%= content %>
</div>
<% end %>
I'm struggling with that helper though, since it involves yielding in the block passed to the method AND yielding to the content in :top_row. Here's what i tried, which doesn't work - it renders the whole page into the returned string. I think i've got it backwards somehow.
def yield_if(content_name, &block)
content = yield content_name
if content.blank?
""
else
yield content
end
end
Yep, there is a content_for? helper just for that of checking.
I looked at the 2.2.2 content_for
and it uses instant_variable_set
for this. May be you can use instance_variable_defined?
to query for your :top_row
content.
Another idea could be to assign the content to a variable <% content = yield(:top_row) %>
and then use content.present?
to circumvent an empty div
.
Since you've no access to content_for?
, the only way to go through this seems to use javascript and remove the div if it's empty.
精彩评论