Ruby on rails 在同一控制器中使用两个不同的布局模板?

Ruby on rails 在同一控制器中使用两个不同的布局模板?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有一个指定了布局为“pages.html.erb”的页面控制器 class PagesController < Spree::StoreController layout 'pages' respond_to :html def lifestyle render 'lifestyle' end def co_step_1 render 'co_step_1' end def co_step_2

我有一个指定了布局为“pages.html.erb”的页面控制器

  class PagesController < Spree::StoreController
    layout 'pages'
    respond_to :html

    def lifestyle
      render 'lifestyle'
    end

    def co_step_1
      render 'co_step_1'
    end

    def co_step_2
      render 'co_step_2'
    end

  end
class PagesController
是否可以在PagesController中使用其他布局的其他方法?
换句话说,我想用另一种方法覆盖pages.html.erb的
布局。

是的。如果需要,可以设置每个控制器的布局

def some_special_method
  render layout: "special_layout"
end

它位于导轨导轨中,非常有用:

是的,您可以指定布局选项

def my_new_layout
  render layout: "my_new_layout"
end

例如,您还可以添加在每个操作之前运行的方法来确定布局

 class PagesController < Spree::StoreController
    before_action :set_layout 
    respond_to :html

    def lifestyle
      render 'lifestyle'
    end

    def co_step_1
      render 'co_step_1'
    end

    def co_step_2
      render 'co_step_2'
    end

    private
    def set_layout
      %w(co_step_1 co_step_2).include?(params[:action]) ? "pages" : "other"
    end
  end
class PagesController
答案与其他答案有点不同。无需进行任何操作或类似操作,只需使用
布局和方法来区分要使用的布局,如:

class PagesController < Spree::StoreController

    layout :resolve_layout
    respond_to :html

    def lifestyle
      render 'lifestyle'
    end

    def co_step_1
      render 'co_step_1'
    end

    def co_step_2
      render 'co_step_2'
    end

   private

   def resolve_layout
     action_name == 'pages' ? 'pages' : 'custom_layout'
   end

end
class PagesController

或者你想用什么逻辑来决定使用哪种布局。

我已经把这弄糊涂了。这将使
app/views/layouts/my_new_layout.html.erb
作为布局,而
app/views/pages/my_new_layout
作为视图文件。您的
set_layout
方法不应该是
%w(co_step_1 co_step_2)。包括?(参数[:动作]?“页面”:“其他”
是的,我应该在咖啡后再回答问题,谢谢。)一种我们都会遭受的痛苦:)这比行动前的钩子要好。它很好用。我在所有页面的应用程序控制器中都使用了它。谢谢