【问题标题】:Add translation to I18N dynamically动态添加翻译到 I18N
【发布时间】:2013-06-12 18:13:39
【问题描述】:

我添加了人性化货币存取器,如下所述:Decimals and commas when entering a number into a Ruby on Rails form

现在我的模型中有两个属性用于相同类型的数据:原始版本和人类可读版本。问题:由于我使用的是activerecord-translation-yml-files,我必须为原始属性和humanized_attribute输入相同的翻译,因为我的表单显示thie humanized_attribute的名称,但在验证错误时,原始名称显示属性。

是否可以动态添加翻译?这样我可以在调用humanized_accessor-class-method时为字段的人性化版本添加翻译,从yml文件中获取原始翻译字符串,而不是将它们(具有相同的值)写入yml -file,只是为了有更多的 DRY。

【问题讨论】:

    标签: ruby-on-rails internationalization ruby-on-rails-3.2 rails-i18n


    【解决方案1】:

    这取决于 I18n gem 的内部 API 不会改变,但可以使用 I18n.backend.store_translations

    这个人为的例子演示了:

    I18n.with_locale(:fake_locale) { I18n.t('some_word') }
      => "translation missing: fake_locale.some_word"
    
    I18n.backend.store_translations(:fake_locale, some_word: 'fake translation')
    
    I18n.with_locale(:fake_locale) { I18n.t('some_word') }
      => "fake translation"
    

    重要提示:这仅在内存中完成。一些持久性或重新生成机制是必要的,以防止这些在您重新部署/重新启动服务器时消失。

    【讨论】:

      【解决方案2】:

      您可能想查看 globalize3 gem。你有 railscast 教程http://railscasts.com/episodes/338-globalize3?view=asciicast

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-31
        相关资源
        最近更新 更多