设计和本地化自己的邮件模板

zac*_*har 8 ruby ruby-on-rails actionmailer internationalization devise

我正在使用devise gem并希望翻译确认邮件.我已经有了自己的模板和重写的邮件方法:

class LocalizedDeviseMailer < Devise::Mailer
  def confirmation_instructions(record, locale)
    @locale = locale
    super
  end
end
Run Code Online (Sandbox Code Playgroud)

所以,在我的模板中我可以这样做:

I18n.locale = @locale
Run Code Online (Sandbox Code Playgroud)

然后:

t("it.really.works")
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将我的变量与locale传递给mailer方法.最好的方法是什么?任何帮助,将不胜感激.

小智 8

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: '...'
  #
Run Code Online (Sandbox Code Playgroud)

这是您需要本地化为任何其他html.erb的正文模板

https://github.com/plataformatec/devise/blob/master/app/views/devise/mailer/confirmation_instructions.html.erb

根据你的新用户将使用sign_up http://yoursite/it/users/sign_uphttp://yoursite/en/users/sign_up(如你会在你的路线为您的本地化应用程序通常做)良好的本地化主题和邮件(在意大利在前一种情况下,在英文后)将被发送.


Mic*_*c92 7

我建议locale您在用户模型中添加一列,然后使用自己的邮件程序.这样,如果您计划设置自己的样式表和from字段或添加其他邮件,您还可以获得更大的灵活性.

config/initializer/devise.rb:

Devise.setup do |config|
  ...
  config.mailer = "UserMailer"
  ...
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)


shi*_*ara 1

我认为最简单的方法是将其添加到记录中。因此,您可以在您的用户中添加区域设置列,或者只需attr_accessor :locale在您的用户模型中添加一个区域设置列

因此,您只需在记录中定义此区域设置并将其与I18n.locale = record.locale