shalini sharma
shalini sharma

Reputation: 95

how to use different layout for different pages in ruby on rails?

i know application.html.erb is the default for every page .i want to use a different layout when user login .i mean the dashboard after login should be of different layout rather than the default one(application.html.erb).

Upvotes: 7

Views: 6774

Answers (6)

Milind
Milind

Reputation: 5112

i wanted two different layouts before signin and after signin,so i have implemented using below code where application_controller changes the layout if user is signed_in else uses different layout.... if you are using devise ,dont forget to add layouts in views/layouts

in application_controller.rb

layout :layout_by_resource
    def layout_by_resource
     unless user_signed_in?
      Rails.logger.info "===========Setting layout as views/layouts/auth.html.erb"
       'auth'
     else
      Rails.logger.info "===========Setting layout as views/layouts/blue.html.erb"
       'basic'
     end
   end

Upvotes: 0

Tien Nguyen
Tien Nguyen

Reputation: 599

If you are using devise gem, and your goal is to use another layout within devise controllers, have a look at their docs

Upvotes: 0

sansarp
sansarp

Reputation: 1466

In your application_controller.rb file do this, hope it helps.

 layout :set_layout
 def set_layout
    if current_user
      'dashboard_layout'
    else
      'default_layout'
    end
 end

Upvotes: 4

Steve Wilhelm
Steve Wilhelm

Reputation: 6260

Details about layouts can be found here.

Using a different layout in the action render call

If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above. Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller. You can do this by passing a :layout option to the render call. For example:

class WeblogController < ActionController::Base
  layout "weblog_standard"

  def help
    render action: "help", layout: "help"
  end
end

This will override the controller-wide “weblog_standard” layout, and will render the help action with the “help” layout instead.

Upvotes: 0

lisowski.r
lisowski.r

Reputation: 3761

Create new layout eg app/views/layouts/dunno.html.erb. Use in controller

class DashboardController < ApplicationController
  layout 'dunno'
end

or per action

class DashboardController < ApplicationController
  def index
    render layout: 'dunno'
  end
end

see docs for details

Upvotes: 16

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do this in application controller, add this code, I am assuming that you are using devise

layout :layout_by_resource

def layout_by_resource
  user_signed_in? ? "my_custom_layout" : "application"
end

Upvotes: 3

Related Questions