【问题标题】:application.html.erb is still not renderingapplication.html.erb 仍未呈现
【发布时间】:2016-02-14 09:27:32
【问题描述】:

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

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

我的路线:

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

没有其他布局。 My Views 文件夹的结构如下:

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

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

我只想在&lt;title&gt; 中显示页面名称,但我什至无法正确呈现纯文本。我怎样才能让它工作,这样我才能正确地在标题中获取控制器变量失败?

【问题讨论】:

    标签: ruby-on-rails ruby views


    【解决方案1】:

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

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

    例子:

    class StaticPagesController < ApplicationController   
      layout 'application'
    
      before_action :load_locals
    
      def load_locals
        @locals = {:page_title => 'Default'}
      end
    
      ...
    end
    

    【讨论】:

    • 是的,你明白了。请问我应该如何创建@locals 以传递给视图?
    • 尝试使用before_action 过滤器,或者只是从所有操作中调用一些常用方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多