Rails不同的Devise Mailer布局为相同的动作 [英] Rails different Devise Mailer layout for the same action
问题描述
Admin
和 Worker
例如在我的Devise确认控制器中,根据用户的配置文件,我需要不同的布局。例如,如果用户具有
- 管理配置文件:呈现管理模板
- 工作人员配置文件:呈现工作者模板
- 两者:渲染另一个模板(混合)
因此,我无法设置布局对于Mailer / Controller,但是我需要将其设置在控制器动作中。假设我有一个帮助器layout_for_user()可以返回给定用户的布局名称。我该怎么用?例如Devise邮件程序?
class MyDeviseMailer< Devise :: Mailer
def confirm_instructions(record,token,options = {})
#根据`layout_for_user(record)``
@token = token
devise_mail ,,:confirm_instructions,opts)
end
end
我必须覆盖 devise_mail
方法
def confirm_instructions
...
@layout = find_layout_for_user(user)
devise_mail(user,:confirmation_instructions,opts)
end
#覆盖以包含自定义布局
def devise_mail(record,action,opts = {})
initialize_from_record(record)
mail(headers_for(action,opts))do |格式|
format.html {渲染布局:@layout}
结束
结束
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
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
这篇关于Rails不同的Devise Mailer布局为相同的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!