本文介绍了当 Rails 中缺少请求的模板时呈现默认模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于插件,我想在 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)和所请求路径的信息(例如users/index、locations/edit).它也应该适用于部分.

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

解决方案

解决方案 2:

在 ApplicationController 中使用rescue_from"

类 ApplicationController > ActionController::Baserescue_from ActionView::MissingTemplate do |exception|# 使用exception.path提取路径信息# 这不适用于部分结尾结尾

缺点:不适用于部分.

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.

So say I call an action 'users/index' if users/index.html.erb does not (or other format) exist, 'default/index.html.erb' should be rendered.

Similarly, If I call an action 'locations/edit' and 'locations/edit.html.erb' does not exist, 'default/edit.html.erb' should be rendered

For partials, If I call an action 'locations/index' and the template 'locations/index.html.erb' calls the partial 'locations/_location' which does not exist, it should render 'default/_object'

The solution is seek gives me access to the templates variables (e.g. @users, @locations) and information on the requested path (e.g. users/index, locations/edit). And it should also work with partials.

I have thought of some options which I'll post below. None of them are completely satisfactory.

解决方案

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.

这篇关于当 Rails 中缺少请求的模板时呈现默认模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 08:15