Rails different Devise Mailer layout for the same action
Asked Answered
S

1

2

I have a model User that has multiple referenced "profiles". A user can have several of those profiles, and each of those profiles should induce a specific layout in emails. Let's consider the profiles Admin and Worker

For example, in my Devise confirmation controller, I need different layouts depending on the profile the user have. For example, if the user has

  • Admin profile : render admin template
  • Worker profile : render worker template
  • Both : render another template (hybrid)

Therefore I cannot set a layout for the Mailer/Controller, but I need to set it inside the controller action. Let's suppose I have a helper layout_for_user() that can return the layout name for a given user. How would I use it ? For example with Devise mailer ?

class MyDeviseMailer < Devise::Mailer
    def confirmation_instructions(record, token, options={})
      # whange layout based on `layout_for_user(record)`
      @token = token
      devise_mail(record, :confirmation_instructions, opts)
    end
end
Sinkhole answered 12/6, 2016 at 22:24 Comment(0)
S
2

I had to override the devise_mail method

def confirmation_instructions
  ...
  @layout = find_layout_for_user(user)
  devise_mail(user, :confirmation_instructions, opts)
end

# Override to include custom layouts
def devise_mail(record, action, opts={})
  initialize_from_record(record)
  mail(headers_for(action, opts)) do |format|
    format.html { render layout: @layout }
  end
end
Sinkhole answered 5/4, 2017 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.