[英]Devise and localized own mail template
我正在使用devise gem并希望翻译确认邮件。 我已经有了自己的模板和重写的邮件方法:
class LocalizedDeviseMailer < Devise::Mailer
def confirmation_instructions(record, locale)
@locale = locale
super
end
end
所以,在我的模板中我可以这样做:
I18n.locale = @locale
然后:
t("it.really.works")
但我不知道如何将我的变量与locale传递给mailer方法。 最好的方法是什么? 任何帮助,将不胜感激。
Devise正在“本地”提供邮件模板的本地化。
看一下设计源代码
https://github.com/plataformatec/devise/blob/master/lib/devise/mailers/helpers.rb在此文件中解释了如何本地化主题(添加到您的语言环境文件)
# Setup a subject doing an I18n lookup. At first, it attemps to set a subject
# based on the current mapping:
#
# en:
# devise:
# mailer:
# confirmation_instructions:
# user_subject: '...'
#
这是你需要本地化的身体模板,就像任何其他html.erb一样
取决于您的新用户是否使用http://yoursite/it/users/sign_up
或http://yoursite/en/users/sign_up
(正如您通常在本地化应用程序的路径中所做的那样) http://yoursite/en/users/sign_up
,这是一个好的本地化主题和将发送邮件(前一种是意大利语,后一种是英语)。
我建议在您的用户模型中添加一个locale
列,并使用您自己的邮件程序。 这样,你也有更多的灵活性,如果您打算设置自己的样式表,并from
字段或添加额外的邮件。
在config/initializer/devise.rb
:
Devise.setup do |config|
...
config.mailer = "UserMailer"
...
end
在app/mailers/user_mailer.rb
class UserMailer < Devise::Mailer
default from: "noreply@yourdomain.com"
def confirmation_instructions(user)
@user = user
set_locale(@user)
mail to: @user.email
end
def reset_password_instructions(user)
@user = user
set_locale(@user)
mail to: @user.email
end
def unlock_instructions(user)
@user = user
set_locale(@user)
mail to: @user.email
end
private
def set_locale(user)
I18n.locale = user.locale || I18n.default_locale
end
end
还有一种方法是添加初始化程序:
require 'devise/mailer'
module Devise
class Mailer
module Localized
%w(
confirmation_instructions
reset_password_instructions
unlock_instructions
).each do |method|
define_method(method) do |resource, *args|
I18n.with_locale(resource.try(:locale)) do
super(resource, *args)
end
end
end
end
prepend Localized
end
end
对于ruby <2.1,您可以使用alias_method_chain
。
我认为最简单的方法是将其添加到记录中。 因此,您可以在User或attr_accessor :locale
添加一个locale列,在User模型中添加一个attr_accessor :locale
因此,您只需要在记录中定义此区域设置,并将其与I18n.locale = record.locale
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.