M Hartl 的 Ruby on Rails 教程第 5 章主页上的自定义标题 [英] M Hartl's Ruby on Rails Tutorial Chapter 5 custom title on home page
问题描述
在 Michael Hartl 的 RoR 教程中:第 5 章末尾的练习涉及简化 RSpec 测试.
In Michael Hartl's RoR tutorial: the exercises at the end of chapter 5 involve simplifying RSpec tests.
5.37 ( http://ruby.railstutorial.org/Chapters/filling-in-the-layout#sec-layout_exercises ) 为主页定义了几个测试.在文件 spec/helpers/application_helper_spec.rb 中:
5.37 ( http://ruby.railstutorial.org/chapters/filling-in-the-layout#sec-layout_exercises ) defines several test for the home page. In the file spec/helpers/application_helper_spec.rb:
require 'spec_helper'
describe ApplicationHelper do
describe "full_title" do
.
.
.
.
it "should not include a bar for the home page" do
full_title("").should_not =~ /\|/
end
end
end
要通过此测试,我需要显示主页标题:Ruby on Rails 教程示例应用程序"而不是Ruby on Rails 教程示例应用程序 | 主页"
For this test to pass, I need to have the Home page title display: "Ruby on Rails Tutorial Sample App" And not "Ruby on Rails Tutorial Sample App | Home"
但是,本教程并未引导我了解如何编写更改代码.
But, the tutorial doesn't walk me through how to code that change.
这是我尝试过的:
在 app/views/static_pages/home.html.erb 中:
In app/views/static_pages/home.html.erb:
删除:
<% provide(:title, 'Home') %>
在 app/views/layouts/application.html.erb将标签编辑为:
In app/views/layouts/application.html.erb Edit the tag to:
<title>
<% if :title
full_title = "Ruby on Rails Tutorial Sample App | " && yield(:title)
else
full_title = "Ruby on Rails Tutorial Sample App"
end %>
<%= print full_title %>
</title>
以及我的菜鸟大脑可以召集的其他变化.这是我想要完成的:
And other variations my noob brain could muster. Here's what I'm trying to accomplish:
如果页面没有提供标题,返回Ruby on Rails Tutorial Sample App"
If the page has no title provided, return "Ruby on Rails Tutorial Sample App"
如果提供了标题,则返回Ruby on Rails 教程示例应用 | #PageTitle"
If there is a title provided, return "Ruby on Rails Tutorial Sample App | #PageTitle"
感谢任何建议.
推荐答案
这个怎么样?
module ApplicationHelper
# Returns the full title on a per-page basis.
def full_title(page_title)
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
"#{base_title} | #{page_title}"
end
end
end
http://ruby.railstutorial.org/chapters/rails-风味红宝石#code-title_helper
只需调用视图中的方法即可.所以它应该是这样的
正如他所说.
Just call the method inside your view.
So it should be something like
<title><%= full_title(yield(:title)) %></title>
as he says.
这篇关于M Hartl 的 Ruby on Rails 教程第 5 章主页上的自定义标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!