【问题标题】:Rails: Translation in InitializerRails:初始化器中的翻译
【发布时间】:2013-02-25 22:43:25
【问题描述】:

我有几个翻译隐藏在初始化器中,如下所示:

GROUP_GOVERNANCE_STYLES = [
  [I18n.t("constants.group_governance_styles.collective"), 1],
  [I18n.t("constants.group_governance_styles.electoral_democracy"), 2],
  [I18n.t("constants.group_governance_styles.dictatorship"), 3]
]

在我的 en.yml 文件中,我有:

en:
  constants:
    group_governance_styles:
      collective: "collective"
      electoral_democracy: "electoral democracy"
      dictatorship: "dictatorship"

不幸的是,当我尝试在视图中呈现这些翻译时,我收到以下错误:

translation missing: en.constants.group_governance_styles.collective
translation missing: en.constants.group_governance_styles.electoral_democracy
translation missing: en.constants.group_governance_styles.dictatorship

我也尝试删除范围,但翻译仍然缺失。还有另一种方法可以解决这个问题吗?也许有一个我不知道的初始化器的默认范围?

【问题讨论】:

    标签: ruby-on-rails translation initializer


    【解决方案1】:

    AFAIK,翻译在初始化程序之后加载。试着把它放在 environment.rb 中

    【讨论】:

    • 这行得通!我对 environment.rb 了解不多,但似乎用像这样的常量填充它可能是一种不好的做法。是否可以从 environment.rb 中加载包含常量的文件?
    • 同意。我也不喜欢向 environment.rb 添加代码。您还可以将该代码放在单独的文件中(可能在 lib 文件夹中?)并在 environment.rb 中要求该文件。
    【解决方案2】:

    如果您希望能够在其他初始化程序文件中使用您的翻译文件,您可以添加一个 I18n 初始化程序。

    config/initializers/i18n.rb

    # Load application custom translations in order to use them in other initializers
    I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
    

    【讨论】:

    • 像魅力一样工作而且很干净:) 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多