时间:2010-07-24 19:37:15

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

8 个答案:

答案 0 :(得分:17)

在Rails 3.2中使用它比以前概述的要复杂一些。如果你的控制器显式声明了一个布局,那么controller.send(:_layout)的结果就是一个String,否则就是一个ActionView :: Template。试试这个:

module ApplicationHelper
  def current_layout
    layout = controller.send(:_layout)
    if layout.instance_of? String
      layout
    else
      File.basename(layout.identifier).split('.').first
    end
  end
end

答案 1 :(得分:6)

对于Rails 4:

controller.send(:_layout)
=> 'application'     

对于Rails 3.2:

controller.send(:_layout)
=> #<ActionView::Template:0x000000082bb788> 

controller.send(:_layout).identifier返回完整路径:

/home/davidm/Documentos/Devel/myapp/app/views/layouts/application.haml

答案 2 :(得分:4)

我认为它应该是核心的,但是现在你可以制作一个帮助方法:

 def current_layout
    controller.send :_layout
  end

它将返回当前使用的布局名称

答案 3 :(得分:4)

in rails 5

这对我有用:

def current_layout
  layout = controller.class.send(:_layout)
  if layout.nil?
    default_layout
  elsif layout.instance_of? String or layout.instance_of? Symbol
    layout
  else
    File.basename(layout.identifier).split('.').first
  end
end

答案 4 :(得分:2)

我在浏览页面中使用过Rails4并获得了重新开始。

controller.send(:_layout)

我希望这有帮助。enter image description here

答案 5 :(得分:0)

你可以在Ajax gem for Rails中完成我用_render_layout方法包装的内容:

    ActionView::Base.class_eval do
      def _render_layout_with_tracking(layout, locals, &block)
        controller.instance_variable_set(:@_rendered_layout, layout)
        _render_layout_without_tracking(layout, locals, &block)
      end
      alias_method_chain :_render_layout, :tracking
    end

然后你可以访问从视图中设置的值(我很确定你可以访问那里的控制器......)或者在after_filter的控制器中访问,这就是我的工作。

我写了一个custom RSpec 2 matcher,可以用来测试Rails 3中的布局渲染。

答案 6 :(得分:0)

先前答案中的所有方法都尝试通过私有方法来猜测名称,但是无需猜测,并且可以使用公共API轻松实现:

class ApplicationController
  layout :set_layout
  attr_reader :layout_name
  helper_method :layout_name

  private

  def set_layout
    @layout_name = "application"
  end
end

覆盖不使用标准布局的任何控制器:

class MyController < ApplicationController
  private

  def set_layout
    @layout_name = "my_layout"
  end
end

现在在您看来:

<%= layout_name %>

答案 7 :(得分:0)

对于Rails 5:

controller.class.send(:_layout)

这不起作用:

controller.send(:_layout)
相关问题