render default template when requested template is missing in Rails

后端 未结 4 982
半阙折子戏
半阙折子戏 2021-01-19 04:19

For a plugin I want to hack the following feature into Rails:

When a (partial) template does not exist (regardless of the format) I want to render a default template

相关标签:
4条回答
  • 2021-01-19 04:54

    I found a patch that is relatively clean, it only patches the lookup of the template which is exactly what was required in the question.

    
    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
    
    0 讨论(0)
  • 2021-01-19 05:03

    Rails 3.1 automatically looks for files in application/template.html.erb after looking in controller/template.html.erb you can see this in the Exception like so:

    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" 
    

    so, just put your default templates in app/views/application

    0 讨论(0)
  • 2021-01-19 05:09

    Solution 2:

    Use 'rescue_from' in ApplicationController

    
    
    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
    
    
    
    

    Drawback: does not work for partials.

    0 讨论(0)
  • 2021-01-19 05:09

    Solution 1:

    Monkey patch 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
    

    This monkey patch requires to look into the (changing) internals of rails and results in ugly code, but probably works.

    0 讨论(0)
提交回复
热议问题