在Rails中缺少请求的模板时呈现默认模板

对于插件,我想将以下function入侵到Rails:

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

所以说如果users / index.html.erb不存在(或其他格式),我会调用动作’users / index’,应该呈现’default / index.html.erb’。

同样,如果我将某个操作称为“位置/编辑”并且“locations / edit.html.erb”不存在,则应显示“default / edit.html.erb”

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

解决方案是seek,允许我访问模板变量(例如@users,@ locations)和所请求路径的信息(例如用户/索引,位置/编辑)。 它也应该与偏见一起使用。

我想到了一些选项,我将在下面发布。 它们都不是完全令人满意的。

解决方案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 

缺点:对部分不起作用。

在查看controller / template.html.erb后,Rails 3.1会自动在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中

我找到了一个相对干净的补丁,它只修补了模板的查找,这正是问题所要求的。

 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 

解决方案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的内部并导致丑陋的代码,但可能有效。