====== 基本用法 ====== Rails默认的Locale文件夹在config/locales下,假设你要支持中文和英语,那么你需要在这个文件夹下放置en.yml和zh.yml。 # zh.yml zh: submit: ‘提交’ create: ‘创建’ #en.yml en: submit: ‘Submit’ create: ‘Create’ Rails 会自动加载config/locales目录下的locale文件,如果你的locale文件放在别的地方,那么你可以通过修改I18n.load_path来加载它: # in config/initializer/locale.rb I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ] 使用很简单,你可以进入Console进行测试: > I18n.t ’submit’ => “Submit” > I18n.locale = ‘zh’ => “zh” > I18n.t(’submit’) => “提交” 试图中更加简单,你可以直接调用t方法: <%= t ’submit’ %> ====== 传递变量 ====== 有些时候,我们的字符串中可能需要包含变量,只需要将其放在两个大括号内就可以了: # zh.yml zh: hello: “你好, {{name}}” 打开console: > I18n.t ‘hello’, :name => ‘Rails’ => “你好,Rails!” ====== 单复数处理 ====== 实际上,中文不存在这个问题,这个问题主要存在于字母语言,解决方法是: # en.yml en: post: one: ‘1 post’ other: ‘{{count}} posts’ 然后在console中测试: > I18n.t ‘post’, :count => 1 => “1 post” > I18n.t ‘post’, :count => 5 => “5 posts” ====== 时间和日期 ====== 时间和日期的翻译稍微复杂,需要用到rails-i18n项目下rails/locale文件夹下的zh-CN.yml文件,由于文件太大,就不贴出来了,有了这个文件,现在你就可以: > I18n.l Date.today, :format => ‘long’ => “2009年1月08日” > I18n.l Time.now, :format => ‘default’ => “2009年1月08日 星期四 20:37:58 CST” > I18n.time_ago_in_words(Time.now) => “一分钟内” > I18n.time_ago_in_words(48.minutes.ago) => “大约一小时” ====== 数字 ====== 假设你已经有了上面的那个文件: > number_to_currency(100) => “$100.00″ > I18n.locale = ‘zh’ => “zh” > number_to_currency(100) => “CNY 100.00″ 你只需要将CNY换成人民币的符号就可以了。 ====== ActiveRecord ====== 假设你有一个user model,它有两个属性login和email,那么需要在zh.yml中定义: zh: activerecord: models: user: “用户” attributes: user: login: “用户名” email: “电邮” 这样就OK了: > u = User.create false > u.errors.full_messages ['用户名不能为空字符', '电邮不能为空字符'] ====== 根据请求设定语言 ====== 要设置应用的默认语言,可以通过 config.i18n.default_locale = :zh 如果要根据用户浏览器的设置选择语言,需要在application.rb中加一个before_filter: class ApplicationController before_fiter :set_language def set_language request_language = request.env['HTTP_ACCEPT_LANGUAGE'] request_language = request_language.nil? ? nil : request_language[/[^,;]+/] I18n.locale = request_language if request_language && File.exist?(”#{RAILS_ROOT}/config/locales/#{request_language}.yml”) end end 参考: * http://rails-i18n.org/wiki/pages/i18n-rails-guide * http://media.railscasts.com/videos/138_i18n.mov * http://blog.ashchan.com/archive/2008/11/24/rails-i18n-activerecord-model-human-name-made-easy/ * http://i18n-demo.phusion.nl/