【问题标题】:Ruby on Rails I18n mailer subject translations in custom directory自定义目录中的 Ruby on Rails I18n 邮件主题翻译
【发布时间】:2018-01-11 12:52:35
【问题描述】:

我正在使用 I18n gem 进行翻译。我将所有翻译都放在一个文件中(en.yml,es.yml..)。 但是对于电子邮件,我不是翻译电子邮件正文中的每个句子,而是为每个区域设置一个单独的电子邮件视图。所以我的电子邮件视图文件的结构如下:

- views
    - user_mailer
      - notify_activation.en.html.erb
      - notify_activation.de.html.erb
      - notify_activation.es.html.erb

我的用户邮件是这样的:

class UserMailer < ApplicationMailer
  def notify_activation user
    @user = user
    mail(to: @user.email, subject: t('mailer.user.activation.subject'))
  end
end

现在我想将邮件主题翻译放在语言环境中的自定义目录中。所以语言环境结构将如下所示:

- config
  - locales
    - en
      - user_mailer.yml
      - *other mailers*.yml
    - de
      - user_mailer.yml
      - *other mailers*.yml
    - es
      - user_mailer.yml
      - *other mailers*.yml
    - devise.en.yml
    - en.yml
    - es.yml
    - de.yml

我搜索了一个解决方案,但都是徒劳的。我遇到了建议我更改 application.rb 中的 i18n.load_path 的解决方案,但这会更改所有翻译的路径,我只想更改邮件主题的加载路径。我希望得到类似的东西:

def load_path
  "#{I18n.locale}/#{self.class_name}"
end

在应用程序 mailer.rb 中。任何解决方案或建议都将受到高度赞赏。

P.S 我对 Rails 很陌生,所以不要介意彻底。

【问题讨论】:

  • 你使用什么 Rails 版本?

标签: ruby-on-rails ruby actionmailer rails-i18n


【解决方案1】:

Rails 自动完成(至少 Rails 4+)。默认的 config/locales/en.yml 有以下注释:

config/locales 目录中的文件用于国际化
并由 Rails 自动加载。如果您想使用其他语言环境
比英文的,在这个目录下添加必要的文件。

因此您可以根据需要在 config 目录中构造文件。

【讨论】:

    【解决方案2】:

    如 Rails 的 I18n 文档中所述: 您可以在config/initializers/application.rb 中更改load_path

    I18n.load_path += Dir[Rails.root.join('config', 'locales', 'en', '*.yml')] 
    I18n.load_path += Dir[Rails.root.join('config', 'locales', 'es', '*.yml')] 
    I18n.load_path += Dir[Rails.root.join('config', 'locales', 'de', '*.yml')] 
    

    【讨论】:

      猜你喜欢
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      相关资源
      最近更新 更多