Ruby on rails 如何在控制器中设置标题?

Ruby on rails 如何在控制器中设置标题?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,View application.html.erb包含以下内容 <title><%= content_for?(:title) ? yield(:title) : t(:stocktaking_title) %></title> Rails 4.1.9,ruby 2.0.0(2014-05-08)[universal.x86_64-darwin14]变量的预填充字符将变量暴露到视图范围中。在控制器中: def show @title = "My Titl

View application.html.erb包含以下内容

<title><%= content_for?(:title) ? yield(:title) : t(:stocktaking_title) %></title>

Rails 4.1.9,ruby 2.0.0(2014-05-08)[universal.x86_64-darwin14]

变量的预填充字符将变量暴露到视图范围中。在控制器中:

def show
  @title = "My Title"
end
将允许任何渲染模板文件使用以下方式访问它:

<%= @title %>
你可以把它压缩成三元,但是这个视图不太可读

如果您坚持在控制器内部为使用
content\u,您可以使用该方法,但您似乎无法像这样直接为
使用
content\u:

view_context.content_for(:title, "My Awesome Title")
相反,您需要为
方法实现自己的
content\u,以扩展
view\u上下文
。我知道,但代码是这样的:

class ApplicationController < ActionController::Base
  ...
  # FORCE to implement content_for in controller
  def view_context
    super.tap do |view|
      (@_content_for || {}).each do |name,content|
        view.content_for name, content
      end
    end
  end
  def content_for(name, content) # no blocks allowed yet
    @_content_for ||= {}
    if @_content_for[name].respond_to?(:<<)
      @_content_for[name] << content
    else
      @_content_for[name] = content
    end
  end
  def content_for?(name)
    @_content_for[name].present?
  end
end

我只想使用symbol
:title
,我不想更改所有内容。在我的情况下不起作用。我更新了问题,它有正确的格式。@zoonman我做了一个有效的更新。我真的不喜欢它和替代品。是的,看起来有人已经把这个补丁放进了gem。这有点可笑。控制器中没有这么简单和常用的东西。
view_context.content_for(:title, "My Awesome Title")
class ApplicationController < ActionController::Base
  ...
  # FORCE to implement content_for in controller
  def view_context
    super.tap do |view|
      (@_content_for || {}).each do |name,content|
        view.content_for name, content
      end
    end
  end
  def content_for(name, content) # no blocks allowed yet
    @_content_for ||= {}
    if @_content_for[name].respond_to?(:<<)
      @_content_for[name] << content
    else
      @_content_for[name] = content
    end
  end
  def content_for?(name)
    @_content_for[name].present?
  end
end
<title><%= @title || content_for(:title) || t(:stocktaking_title) %></title>