Rendering different layouts in Rails depending on whether the user is logged in
August 9, 2020 (Updated April 13, 2021)
Assuming we have two different layout files:
application.html.erb
- for logged in usersguest.html.erb
- for guest users
We can add the following bit of code in our base ApplicationController
:
class ApplicationController < ActionController::Base
layout :layout
private
def layout
user_signed_in? ? 'application' : 'guest'
end
end
Assuming all our custom controllers extend ApplicationController
as is the default convention, then our views will use the application
layout when the user is signed in and the guest
layout when they aren't signed in.
Tagged:
Rails