我希望能够在 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/