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

标签 ruby-on-rails ruby

在 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 教程示例应用程序 | 主页”

但是,本教程并未指导我完成如何对更改进行编码。

这是我尝试过的:

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

  1. 删除:

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

以及我的菜鸟大脑可以召集的其他变体。 这是我要实现的目标:

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

如果提供了标题,则返回“Ruby on Rails 教程示例应用程序 | #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

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

关于ruby-on-rails - M Hartl 的 Ruby on Rails 教程第 5 章主页自定义标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13731391/

相关文章:

javascript - 如何在 Rails 中使用带有 anchor 的 Ajax 链接

ruby-on-rails - Rails 应用程序的共享文件存储

ruby-on-rails - 添加标签到输入

ruby - Mechanize 发送 POST 以填充页面上的数据

ruby-on-rails - Rails Vuejs Webpacker : Passing instance variable data

ruby-on-rails - 在 Ruby on Rails 中使用 Savon 的 SOAP 调用在信封和主要操作周围变得奇怪

ruby - 升级 Rails 设计

ruby-on-rails - 名称已被 Ruby on Rails 使用或保留?

mysql - Rails 4.2 Query 3模型以及belongs_to和has_one无法根据子属性获取父级

mysql - 在嵌套连接表上调用 uniq