application.html.erb 仍然没有渲染

application.html.erb is still not rendering

我生成了一个 Rails 应用程序,正在研究内部结构。以前我的 application.html.erb 渲染正确,但现在 Rails 似乎完全忽略了它,因为它甚至不会产生错误。

Stack Overflow 上有很多关于这个问题的问题。我查看了我认为的所有内容,但 none 有所帮助。

我的路线:

Rails.application.routes.draw do

  # static_pages from rails tutorial ch. 3
  get 'static_pages/home'
  get 'static_pages/help'
  get 'static_pages/about'

end

这里是views/layout/application.html.erb

<!DOCTYPE html>
<html>
    <head>
        <title>This Title is not showing up</title>
        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
        <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
        <%= csrf_meta_tags %>
    </head>
    <body>
    <p> why isnt this showing up?? </p>
        <%= yield %>

    </body>
</html>

这里是 static_pages_controller:

class StaticPagesController < ApplicationController   
    layout 'application' #<- I know this shouldn't be necessary, but I thought i'd try

    def initialize
        @locals = {:page_title => 'Default'}
    end

    def about
        @locals[:page_title] = 'About'
        render @locals
    end

    def help
        @locals[:page_title] = 'Help'
        render @locals
    end

    def home
        @locals[:page_title] = 'Home'
        render @locals
    end

end

这是应用程序控制器:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

没有其他布局。我的 Views 文件夹具有以下结构:

-Views
 |-layouts
 ||-application.html.erb
 |
 |-static_pages
 ||-about.html.erb
 ||-home.html.erb
 ||-help.html.erb

我曾尝试在 application.html.erb 中故意生成错误,调用不存在的变量以及任何其他恶作剧。 Rails完全不理我,我很没有安全感。

我只想在 <title> 中显示页面名称,但我什至无法正确呈现明文。我怎样才能让它工作,以便我可以正确地在标题中获取控制器变量失败?

您不应覆盖控制器 initialize 方法。这样做会破坏基本 class 行为。

虽然我相信,只需从 initialize 调用 super 即可解决您的问题,但为特定操作初始化控制器的正确 Rails 方法是使用before filter 相反。

示例:

class StaticPagesController < ApplicationController   
  layout 'application'

  before_action :load_locals

  def load_locals
    @locals = {:page_title => 'Default'}
  end

  ...
end