ruby-on-rails - i18n 复数化

标签 ruby-on-rails internationalization rails-i18n pluralize plural

我希望能够在 Rails 中翻译 i18n 中的复数字符串。字符串可以是:

You have 2 kids

You have 1 kid

我知道我可以使用复数辅助方法,但我想将其嵌入到 i18n 翻译中,这样我就不必在将来的任何时候弄乱我的观点。我读到 :count 在某种程度上用于复数翻译,但我找不到任何关于它如何实现的真正资源。

请注意,我知道我可以在翻译字符串中传递变量。我也尝试过类似的方法:

<%= t 'misc.kids', :kids_num => pluralize(1, 'kid') %>

这工作得很好,但有一个相同想法的基本问题。我需要在复数帮助器中指定字符串 'kid' 。我不想这样做,因为这会导致将来的 View 问题。相反,我想保留翻译中的所有内容,而不保留 View 中的任何内容。

我怎样才能做到这一点?

最佳答案

试试这个:

en.yml:

en:
  misc:
    kids:
      zero: no kids
      one: 1 kid
      other: %{count} kids

在 View 中:

You have <%= t('misc.kids', :count => 4) %>
<小时/>

更新了具有多个复数形式的语言的答案(使用 Rails 3.0.7 测试):

文件 config/initializers/pluralization.rb:

require "i18n/backend/pluralization" 
I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)

文件 config/locales/plurals.rb:

{:ru => 
  { :i18n => 
    { :plural => 
      { :keys => [:one, :few, :other],
        :rule => lambda { |n| 
          if n == 1
            :one
          else
            if [2, 3, 4].include?(n % 10) && 
               ![12, 13, 14].include?(n % 100) && 
               ![22, 23, 24].include?(n % 100)

              :few 
            else
              :other 
            end
          end
        } 
      } 
    } 
  } 
}

#More rules in this file: https://github.com/svenfuchs/i18n/blob/master/test/test_data/locales/plurals.rb
#(copy the file into `config/locales`)

文件 config/locales/en.yml:

en:
  kids:
    zero: en_zero
    one: en_one
    other: en_other

文件 config/locales/ru.yml:

ru:
  kids:
    zero: ru_zero
    one: ru_one
    few: ru_few
    other: ru_other

测试:

$ rails c
>> I18n.translate :kids, :count => 1
=> "en_one"
>> I18n.translate :kids, :count => 3
=> "en_other"
>> I18n.locale = :ru
=> :ru
>> I18n.translate :kids, :count => 1
=> "ru_one"
>> I18n.translate :kids, :count => 3
=> "ru_few"  #works! yay! 
>> I18n.translate :kids, :count => 5
=> "ru_other"  #works! yay! 

关于ruby-on-rails - i18n 复数化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6166064/

相关文章:

ruby-on-rails - rails 找不到 rake gem

svn - 如何使用 utf-8 消息文件提交?

ruby-on-rails - Rails I18n 中的惰性查找是一种不好的做法吗?

ruby-on-rails - Rails i18n 方法导致段错误?

ios - 如果不使用 genstrings,NSLocalizedString 比 localizedStringForKey :value:table:? 有任何好处

javascript - 热从 .js.erb 文件获取 I18.locale?

ruby-on-rails - rails 5.1 : retrieve records for nested association with includes

ruby-on-rails - Heroku 拒绝了我的 git 推送请求

ruby-on-rails - Rails Devise PG::SyntaxError: ERROR: ""处或附近的零长度分隔标识符“”

ruby-on-rails - 为 i18n 设计属性?