简体   繁体   中英

Change layout for Devise controllers

I am using gem devise . Devise extends application controller and adds user managment to rails application.

When I look inside the gem I can see following line

class Devise::SessionsController < ApplicationController

I am trying to change this since I want Devise controller to inherit from my custom controller named AdminController . Reason for this is I have whole web application finished and I do not want admin part of the page to use my application layout, css, js ...

How can I dynamically change base class of controller? Or dynamically tell controller to use admin.html.erb layout instead of application.html.erb layout.

When I say "dynamicly" I mean monkey patch it, thank you.

Devise is a rails engine . I think that the best way to make a admin section of you site is to make a rails engine. Or better still use rails_admin or activeadmin . They are both rails engines There is a railscast about rails engines

I don't know the inner works of you app, but if you add

layout "admin"

to your AdminController and add a custom admin layout to the view/layouts folder with

 <%= stylesheet_link_tag 'admin' %>
 <%= javascript_include_tag "admin"%>

the AdminController views will use the admin stylesheet and javascript

This solved my problem, if namespace of controller is Devise use admin layout.

class ApplicationController < ActionController::Base
  protect_from_forgery

  layout :determine_layout

  def determine_layout
    module_name = self.class.to_s.split("::").first
    return (module_name.eql?("Devise") ? "admin" : "application")
  end
end

If you just need to change the layout, I think you should be able to do it by re-opening the controller class. At the bottom of your initializers/devise.rb (underneath the config section at the top level, you could write:

Devise::SessionsController.layout :admin

I've not tried this, but in theory it should work since layout is just a class method on ActionController.base.

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