国际化 [英] i18n Pluralization

查看:108
本文介绍了国际化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to translate pluralized strings in i18n in rails. A string can be :

You have 2 kids

You have 1 kid

我知道我可以使用复数辅助方法,但是我想将此方法嵌入到i18n转换中,以便将来在任何时候都不必弄乱我的观点.我读到:count在某种意义上用于复数形式的翻译,但是我找不到关于如何实现它的任何真正的资源.

I know that I can use pluralize helper method, but I want to embed this in i18n translations so that I don't have to mess up with my views at any point in the future. I read that :count is somehow used in translations for plural, but I can't find any real resources on how it gets implemented.

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

Notice that I know that I can pass a variable in a translation string. I also tried something like :

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

哪个工作正常,但存在一个基本思路相同的问题.我需要在复数助手中指定字符串'kid'.我不想这样做,因为它将导致将来出现问题.相反,我想将所有内容保留在翻译中,而将所有内容保留在视图中.

Which works fine, but has a fundamental problem of the same idea. I need to specify the string 'kid' in the pluralize helper. I don't want to do that because it will lead to view problems in the future. Instead I want to keep everything in the translation and nothing in the view.

我该怎么做?

推荐答案

尝试一下:

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! 

这篇关于国际化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆