0

我正在关注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

请问有什么见解吗?

4

1 回答 1

1

我认为你应该简化:

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

application_helper.rb

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

现在,我不认为你真的想要“测试”......真的,我认为你只是不想在 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.
于 2012-09-03T22:28:28.297 回答