Use a layout for a specific action

后端 未结 3 552
遥遥无期
遥遥无期 2020-12-29 19:24

If I would like to use a layout for a certain action (say, the show action) that is different from the layout declared at the top of the controller.rb file, how could I do t

相关标签:
3条回答
  • 2020-12-29 19:57

    Following example applies desired layout to specific action, otherwise, it uses default layout (layouts/application.html.erb).

    class ArticlesController < ApplicationController
       layout "article_editor", only: [:new, :edit]
    
       def index
         # default layout
       end
    
       def new
         # article_editor layout
       end
    
       def edit
         # article_editor layout
       end
    end
    
    0 讨论(0)
  • 2020-12-29 20:13
    layout 'layout', :only => [:first_action, :second_action]
    layout 'second_layout', :only => [:third_action, :fourth_action]
    

    Don's is right as well, just depends on your application which is more DRY (or DRY-er?)


    EDIT My previous code is mistaken. You cannot specify the layout function multiple times. I found this solution online for dynamic layout rendering:

    class OrdersController < BaseController
      layout :determine_layout
    
    private
      def determine_layout
        %w(new).include?(action_name) ? "some_layout" : "public"
      end
    end
    

    Source: apidock.com/rails/Actio...

    0 讨论(0)
  • 2020-12-29 20:21
      render :layout => 'otherlayout'
    
    0 讨论(0)
提交回复
热议问题