【问题标题】:M Hartl's Ruby on Rails Tutorial Chapter 5 custom title on home pageM Hartl 的 Ruby on Rails 教程第 5 章主页自定义标题
【发布时间】:2012-12-05 20:00:01
【问题描述】:

在 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 Tutorial Sample App | #PageTitle”

欢迎提出任何建议。

【问题讨论】:

  • 作为快速评论,您应该在控制器中设置一些值@full_title = ___。然后你可以做额外的条件(仍然在控制器中),例如,如果有一个标题,你可以连接栏和标题。
  • @wrhall 我很感激。我试过 @full_title 和 :full_title 无济于事。我也试过&lt;%= yield(@full_title) %&gt; 而不是&lt;%= print @full_title %&gt;
  • 您回滚改进帖子的编辑有什么原因?
  • 如果我觉得您的编辑改进了帖子的语法或布局,我会接受。
  • @Chiperific 我目前正在“清理”所有带有[home] 标签的帖子(为销毁做准备),根据政策,这需要我修复/改进 all 部分帖子...

标签: ruby-on-rails ruby


【解决方案1】:

这个怎么样?

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

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

【讨论】:

  • 哇。我翻遍了第 3 章和第 4 章,不知何故错过了这一点。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多