sa125
sa125

Reputation: 28971

Rails - How can I detect if the content_for content was provided?

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

Answers (5)

Brenes
Brenes

Reputation: 351

In an old Rails 2.1.1,

<%= (yield :title) || default_title %>

is working for me.

Upvotes: 2

Tadas T
Tadas T

Reputation: 2637

One more way

'common/top_status') %>

Upvotes: 1

Toby Hede
Toby Hede

Reputation: 37143

You can streamline the code further:

def content_exists?(name)
  return instance_variable_get("@content_for_#{name}")
end

Upvotes: 3

sa125
sa125

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

John Topley
John Topley

Reputation: 115432

Try this:

<title>
  <%= yield :title || "404 - Page Unknown" -%>
</title>

Upvotes: 2

Related Questions