ruby-on-rails – M Hartl的Ruby on Rails教程第5章主页上的自定义标题

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – M Hartl的Ruby on Rails教程第5章主页上的自定义标题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@在Michael Hartl的RoR教程中:第5章末尾的练习涉及简化RSpec测试.

5.37(http://ruby.railstutorial.org/chapters/filling-in-the-layout#sec-layout_exercises)定义了主页的几个测试.
文件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 Tutorial Sample App | Home”

但是,本教程并未指导我如何编写更改代码.

这是我尝试过的:

在app / views / static_pages / home.html.erb中:

>删除

<%provide(:title,'Home')%>

在app / views / layouts / application.html.erb中
代码编辑为:

<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>

我的noob大脑的其他变化可以集合.
这是我想要完成的事情:

如果页面没有提供标题,请返回“Ruby on Rails Tutorial Sample App”

如果提供了标题,则返回“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-flavored-ruby#code-title_helper

只需在视图中调用方法即可.所以它应该是这样的< title><%= full_title(yield(:title))%>< / title>正如他所说.

原文链接:https://www.f2er.com/ruby/271398.html

猜你在找的Ruby相关文章