Kiran
Kiran

Reputation: 5526

rails not updating page title

I am following railscasts to update custom page title and realized that it doesn't work anymore. So, i updated the code as follows based on the comments. I see 'My Services -' if i do not set the title, whereas i expect it to contain default title value set. Any insights please?

In application.html.erb:

<!DOCTYPE html>
<html>
<%= render 'layouts/head' %>
<!-- <body> included in yield -->
  <%= yield %>
<!-- </body> -->
</html>

In _head.html.erb

<head>
  <title>My services - <%= yield(:title) %> </title>
</head>

In home.html.erb [Intentionally not setting title to see default value]

<body></body>

In application_helper.rb

  def title(page_title, default="Testing")
    content_for(:title) { page_title || default }
  end

In application_helper.rb, I also tried the following solution:

  def title(page_title)
    content_for(:title) { page_title || default }
  end

  def yield_for(section, default = "Testing")
    content_for?(section) ? yield(section) : default
  end

Any insights please?

Upvotes: 0

Views: 430

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

I think you should simplify:

<title>My services - <%= page_title %> </title>

application_helper.rb

def page_title
  if content_for?(:title)
    content_for(:title)
  else
    "Testing"
  end
end

Now, I don't think you actually want "Testing"... Really, I think you just want to not see the "-" at the end of your html page titles. So why not:

<title><%= html_title %></title>

def html_title
  site_name = "My services"
  page_title = content_for(:title) if content_for?(:title)
  [site_name,page_title].join(" - ")
end

You'll either see:

<title>My services</title>

or if you set the title like so:

<%= content_for(:title) { "SuperHero" } %>

You'll see:

<title>My services - SuperHero</title>

#content_for? is defined as:

#content_for? simply checks whether any content has been captured yet using #content_for Useful to render parts of your layout differently based on what is in your views.

Upvotes: 1

Related Questions