views:

127

answers:

4

Hi - I want to detect if content was provided for content_for tag in my template, and if not fall back to default value:

<title>
  <% if content_is_provided -%>
    <%= yield :title -%>
  <% else -%>
    404 - Page Unknown
  <% end -%>
</title>

Any easy way to detect this? I tried <% if :title -%> but that didn't do much. thanks.

+2  A: 

Try this:

<title>
  <%= yield :title || "404 - Page Unknown" -%>
</title>
John Topley
Sadly, this doesn't seem to work for me (no title is echoed). I appreciate the help!
sa125
+1  A: 

After digging in the content_for code a bit, I found a working solution by creating a helper method:

def content_exists?(name)
  return true if instance_variable_get("@content_for_#{name}")
  return false # I like to be explicit :)
end

and in the view:

<% if content_exists?(:title)-%>
  <%= yield :title %>
<% else -%>
  404 - Page Unknown
<% end -%>

This seems to be working, for now (Rails 2.3.5).

sa125
+2  A: 

You can streamline the code further:

def content_exists?(name)
  return instance_variable_get("@content_for_#{name}")
end
Toby Hede
+1  A: 

One more way <%= (top_status = yield :top_status) ? top_status : render(:partial => 'common/top_status') %>

Tadas Tamosauskas