Reputation: 28971
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.
Upvotes: 4
Views: 734
Reputation: 351
In an old Rails 2.1.1,
<%= (yield :title) || default_title %>
is working for me.
Upvotes: 2
Reputation: 37143
You can streamline the code further:
def content_exists?(name)
return instance_variable_get("@content_for_#{name}")
end
Upvotes: 3
Reputation: 28971
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).
Upvotes: 1
Reputation: 115432
Try this:
<title>
<%= yield :title || "404 - Page Unknown" -%>
</title>
Upvotes: 2