简体   繁体   中英

Setting a different Rails template if a user is logged in

I am trying to set the layout to "private" when the user is logged in. It would be perfect if I could do something like:

layout 'private' if current_user

Except it gives this error:

undefined local variable or method `current_user' for ApplicationController:Class

I've also tried doing this in the application controller:

before_filter :pick_the_layout

def pick_the_layout
  if current_user
    render :layout => "private"
  else
    render :layout => "public"
  end
end

No luck with that one, either, which makes sense. Can anyone think of a better way to do this?

You can do it like this:

layout :determine_layout

private
  def determine_layout
    current_user ? "private" : "public"
  end

Obviously, this depends on current_user being nil or false if the user is not logged in.

You can see documentation for the usage of layout here:

http://api.rubyonrails.org/classes/AbstractController/Layouts/ClassMethods.html#method-i-layout

and here with more examples:

http://api.rubyonrails.org/classes/AbstractController/Layouts.html

嗯... layout 'private' if defined?(current_user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM