【问题标题】:Rails i18n - how to get all translations for a keyRails i18n - 如何获取密钥的所有翻译
【发布时间】:2017-01-05 17:06:56
【问题描述】:

我的翻译按正常方式组织:

en:
  foo:
    bar: 'hello friend'
es:
  foo:
    bar: 'hola amigo'

我需要返回给定键的所有翻译的哈希,语言作为哈希的键,如下所示:

# translations for foo.bar
{
  en: 'hello friend',
  es: 'hola amigo'
}

如何从 i18n 引擎中提取它?

【问题讨论】:

    标签: ruby-on-rails internationalization


    【解决方案1】:

    回答我自己的问题,以防万一有人感兴趣。可能不是解决问题的最有效方法,但可以这样做:

    Hash[
      I18n.available_locales.map{|locale|
        [locale, I18n.translate('foo.bar', default: '', locale: locale)]
      }
    ]
    

    【讨论】:

      【解决方案2】:

      您确实可以使用I18n 提取给定键的所有翻译:

      key = 'hello'
      I18n.available_locales.reduce({}) do |acc, locale|
        acc[locale] = I18n.with_locale(locale) { I18n.t(key) }; acc
      end
      

      【讨论】:

      • 我们同时回答。你的也可以。
      猜你喜欢
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2011-04-18
      • 2015-04-20
      • 1970-01-01
      相关资源
      最近更新 更多