【问题标题】:render default template when requested template is missing in Rails在 Rails 中缺少请求的模板时呈现默认模板
【发布时间】:2010-10-25 12:14:08
【问题描述】:

对于一个插件,我想在 Rails 中加入以下功能:

当(部分)模板不存在时(无论格式如何),我想呈现默认模板。

假设如果 users/index.html.erb 不存在(或其他格式),我将操作称为“users/index”,则应该呈现“default/index.html.erb”。

同样,如果我调用操作“locations/edit”并且“locations/edit.html.erb”不存在,则应该呈现“default/edit.html.erb”

对于局部,如果我调用一个动作'locations/index'并且模板'locations/index.html.erb'调用不存在的局部'locations/_location',它应该呈现'default/_object'

解决方案是 seek 让我可以访问模板变量(例如@users、@locations)和有关请求路径的信息(例如用户/索引、位置/编辑)。它也应该适用于部分。

我想到了一些选项,我将在下面发布。没有一个是完全令人满意的。

【问题讨论】:

    标签: ruby-on-rails render actionview


    【解决方案1】:

    Rails 3.1 在查看 controller/template.html.erb 后会自动在 application/template.html.erb 中查找文件,您可以在 Exception 中看到,如下所示:

    Missing template [controller name]/index, application/index with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:erb, :coffee, :builder]}. Searched in: * "/path/to/rails_project/app/views" 
    

    所以,只需将您的默认模板放在 app/views/application 中

    【讨论】:

      【解决方案2】:

      我找到了一个比较干净的补丁,它只修补了模板的查找,这正是问题中需要的。

      
      module ActionView
        class PathSet
      
          def find_template_with_exception_handling(original_template_path, format = nil, html_fallback = true)
            begin
              find_template_without_exception_handling(original_template_path, format, html_fallback)
            rescue ActionView::MissingTemplate => e
              # Do something with original_template_path, format, html_fallback
              raise e
            end
          end
          alias_method_chain :find_template, :exception_handling
      
        end
      end
      

      【讨论】:

        【解决方案3】:

        解决方案 2:

        在 ApplicationController 中使用“rescue_from”

        class ApplicationController > ActionController::Base rescue_from ActionView::MissingTemplate do |exception| # use exception.path to extract the path information # This does not work for partials end end

        缺点:不适用于局部。

        【讨论】:

          【解决方案4】:

          解决方案 1:

          猴子补丁 ActionView::Base#render

          
          module ActionView
            class Base
              def render_with_template_missing(*args, &block)
                # do something if template does not exist
          
                render_without_template_missing(*args, &block)
              end
              alias_method_chain :render, :template_missing
            end
          end
          

          这个猴子补丁需要查看 Rails 的(不断变化的)内部结构并导致代码丑陋,但可能有效。

          【讨论】:

            猜你喜欢
            • 2015-07-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-22
            • 2013-01-12
            • 1970-01-01
            相关资源
            最近更新 更多