StandardNerd
StandardNerd

Reputation: 4183

rails two different layout templates in same controller?

I have a PagesController with a layout 'pages.html.erb' specified.

  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

Is it possible to have an additional method in PagesController that uses a different layout? In other words i want to override the layout 'pages.html.erb' in an additional method.

Upvotes: 5

Views: 2267

Answers (4)

Aleks
Aleks

Reputation: 5320

A bit different answer from the others. No need for before actions or similar, just use a layout and method to distinguish which layout to use, like:

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

Or whatever logic you want to use to decide which layout to use.

Upvotes: 9

trh
trh

Reputation: 7339

You can also add a method that runs before each action to determine the layout, for example

 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

Upvotes: 1

j-dexx
j-dexx

Reputation: 10406

Yes you can specify the layout option

def my_new_layout
  render layout: "my_new_layout"
end

Upvotes: 2

John Paul Ashenfelter
John Paul Ashenfelter

Reputation: 3143

Yes. You can set the layout per controller if you want.

def some_special_method
  render layout: "special_layout"
end

Which is in the Rails guides which are super useful: http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

Upvotes: 2

Related Questions