简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM