我正在关注railscasts更新自定义页面标题,并意识到它不再起作用。所以,我根据评论更新了如下代码。如果我没有设置标题,我会看到“我的服务 - ”,而我希望它包含默认的标题值集。有什么见解吗?
在application.html.erb
:
<!DOCTYPE html>
<html>
<%= render 'layouts/head' %>
<!-- <body> included in yield -->
<%= yield %>
<!-- </body> -->
</html>
在_head.html.erb
<head>
<title>My services - <%= yield(:title) %> </title>
</head>
在home.html.erb
[故意不设置标题以查看默认值]
<body></body>
在application_helper.rb
def title(page_title, default="Testing")
content_for(:title) { page_title || default }
end
在application_helper.rb
中,我也尝试了以下解决方案:
def title(page_title)
content_for(:title) { page_title || default }
end
def yield_for(section, default = "Testing")
content_for?(section) ? yield(section) : default
end
有什么见解吗?
答案 0 :(得分:1)
我认为你应该简化:
<title>My services - <%= page_title %> </title>
application_helper.rb
def page_title
if content_for?(:title)
content_for(:title)
else
"Testing"
end
end
现在,我并不认为你真的想要&#34;测试&#34; ...真的,我认为你只是想看不到&#34; - &#34;在你的HTML页面标题的末尾。那么为什么不呢:
<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
你会看到:
<title>My services</title>
或者如果你设置标题:
<%= content_for(:title) { "SuperHero" } %>
你会看到:
<title>My services - SuperHero</title>
#content_for?定义为:
#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.