我希望能够在rails中翻译i18n中的复数字符串。字符串可以是:
You have 2 kids或
You have 1 kid我知道我可以使用method helper方法,但我想将其嵌入到i18n翻译中,这样我就不会在未来的任何时候搞砸我的视图。我读到:count以某种方式用于复数的翻译,但我找不到任何关于它是如何实现的真正资源。
请注意,我知道我可以在转换字符串中传递变量。我还尝试了一些类似的东西:
<%= t 'misc.kids', :kids_num => pluralize(1, 'kid') %>它工作得很好,但有一个基本的问题,就是同样的想法。我需要在'kid' helper中指定字符串'kid'。我不想这样做,因为这会导致未来的视图问题。相反,我想保留翻译中的所有内容,而不是视图中的任何内容。
我该怎么做呢?
发布于 2011-05-29 13:13:55
试试这个:
en.yml:
en:
misc:
kids:
zero: no kids
one: 1 kid
other: %{count} kids在视图中:
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! 发布于 2014-11-18 02:55:21
我希望讲俄语的Ruby on Rails程序员能找到这一点。只想分享我自己非常精确的俄语复数公式。它是基于Unicode Specs的。这里只是config/locales/plurals.rb文件的内容,其他的一切都应该和上面的答案一样。
{:ru =>
{ :i18n =>
{ :plural =>
{ :keys => [:zero, :one, :few, :many],
:rule => lambda { |n|
if n == 0
:zero
elsif
( ( n % 10 ) == 1 ) && ( ( n % 100 != 11 ) )
# 1, 21, 31, 41, 51, 61...
:one
elsif
( [2, 3, 4].include?(n % 10) \
&& ![12, 13, 14].include?(n % 100) )
# 2-4, 22-24, 32-34...
:few
elsif ( (n % 10) == 0 || \
![5, 6, 7, 8, 9].include?(n % 10) || \
![11, 12, 13, 14].include?(n % 100) )
# 0, 5-20, 25-30, 35-40...
:many
end
}
}
}
}
}以英语为母语的人可能喜欢111和121这样的大小写。下面是测试结果:
零:0запросов/куриц/яблок
感谢您的初步答复!
发布于 2011-05-29 14:07:17
首先,记住复数形式的数量取决于语言,英语有两种,罗马尼亚语有3种,阿拉伯语有6种!
如果你想正确地使用复数形式,你必须使用gettext。
对于Ruby和rails,您应该检查此http://www.yotabanana.com/hiki/ruby-gettext-howto-rails.html
https://stackoverflow.com/questions/6166064
复制相似问题