[英]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.