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

4 ruby-on-rails render actionview

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

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

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

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

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

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

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

小智 11

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



缺点:对部分不起作用.