从响应者设置布局?

时间:2010-11-21 04:21:07

标签: ruby-on-rails ruby layout ruby-on-rails-3 responders

我想弄清楚如何从自定义响应器设置布局。我想使用request.xhr?将渲染的布局设置为'ajax'。有谁知道怎么做? 我正在使用Rails 3,我有一个像这样的响应者:

module AjaxLayoutResponder
  def to_html
    if request.xhr?
      # do something here to change layout...
    end
    super
  end
end

在我看来,响应者是实现这种“ajax”布局切换的最佳方式。

2 个答案:

答案 0 :(得分:1)

我不同意响应者是要走的路。这是我在大多数项目中使用的简单解决方案(但是我只是将ajax布局设置为nil):

在application_controller.rb

layout :set_layout

def set_layout
  request.xhr? 'ajax' : 'application'
end

答案 1 :(得分:0)

你可以这样做:

module AjaxLayoutResponder
  def to_html
    if request.xhr?
      options[:layout] = 'ajax'
    end
    super
  end
end

因为在响应者执行结束时调用的是:

# from https://github.com/plataformatec/responders/blob/master/lib/action_controller/responder.rb
def default_render
  if @default_response
    @default_response.call(options)
  else
    controller.render(options)
  end
end