Conditionally render different layouts in Rails
11 March 2022 (Updated 1 May 2022)
Suppose you have two different layout files:
application.html.erb
: for logged in usersguest.html.erb
: for guest users
You can add the following to your base ApplicationController
to render a different layout based on the user’s authentication status:
class ApplicationController < ActionController::Base
layout :layout
private
def layout
user_signed_in? ? 'application' : 'guest'
end
end
Assuming your controllers extend ApplicationController
(as is the default convention), your views will use the application
layout when the user is signed in and the guest
layout when they aren’t signed in.
Tagged:
Rails
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment