
Rails i18n:Ruby on Rails 国际化完整指南
从第一个区域设置文件到生产环境:配置 Rails I18n、使用 t() 辅助函数、处理 CLDR 复数、修复常见问题,并添加智能区域设置回退链。
了解 Rails I18n 架构
Rails 内置 I18n gem。翻译文件以 YAML(默认)或 Ruby 文件形式存放在 config/locales/。框架在视图、控制器、模型和邮件程序中提供 t() 辅助函数(I18n.translate 的别名)。Rails I18n 设计简洁,开箱即用地处理基本翻译、插值和复数。
# Rails includes i18n out of the box via the i18n gem
# config/application.rb
module MyApp
class Application < Rails::Application
# Default locale
config.i18n.default_locale = :en
# Available locales
config.i18n.available_locales = [:en, :de, :ja, :es, :fr, :'pt-BR']
# Fallback to default locale when translation is missing
config.i18n.fallbacks = true
# Load translations from nested directories
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
end
end# config/routes.rb
Rails.application.routes.draw do
scope "/:locale", locale: /en|de|ja|es|fr|pt-BR/ do
root "home#index"
resources :products
end
root "home#index"
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
around_action :switch_locale
private
def switch_locale(&action)
locale = params[:locale] || I18n.default_locale
I18n.with_locale(locale, &action)
end
def default_url_options
{ locale: I18n.locale }
end
end配置区域设置
在 config/application.rb 或初始化程序中设置 default_locale、available_locales 和回退行为。在 ApplicationController 中使用 before_action 配置区域设置检测,从 URL、会话、Cookie 或 Accept-Language 标头设置区域设置。
# config/locales/en.yml
en:
nav:
home: "Home"
about: "About"
settings: "Settings"
greeting: "Hello, %{name}!"
cart:
item_count:
one: "%{count} item"
other: "%{count} items"
# config/locales/de.yml
de:
nav:
home: "Startseite"
about: "Über uns"
settings: "Einstellungen"
greeting: "Hallo, %{name}!"
cart:
item_count:
one: "%{count} Artikel"
other: "%{count} Artikel"使用 t() 辅助函数
t() 辅助函数可用于 Rails 的任何位置:视图、控制器、模型、邮件程序和作业。它接收键、可选插值变量,以及默认值和作用域等选项。在视图中,Rails 支持惰性查找,自动将键限定到当前控制器和操作。
# In views (ERB)
<h1><%= t('nav.home') %></h1>
<p><%= t('greeting', name: @user.name) %></p>
# In controllers
flash[:notice] = t('flash.product_created')
# In models
validates :name, presence: { message: I18n.t('errors.blank') }
# With HTML (safe)
<%= t('terms_html', link: link_to(t('terms_link'), '/terms')) %>处理复数
Rails I18n 使用 CLDR 复数类别:zero、one、two、few、many、other。英语只需要 one 和 other,其他语言则需要更多形式。将复数翻译定义为目标语言所需 count 类别下的嵌套 YAML 键。
# In YAML:
en:
cart:
item_count:
zero: "No items"
one: "%{count} item"
other: "%{count} items"
# Arabic (6 forms):
ar:
cart:
item_count:
zero: "لا عناصر"
one: "عنصر واحد"
two: "عنصران"
few: "%{count} عناصر"
many: "%{count} عنصرًا"
other: "%{count} عنصر"
# Usage in views:
<%= t('cart.item_count', count: @cart.items.size) %>添加区域设置回退链
Rails 内置的 I18n.fallbacks 只提供从地区区域设置到默认区域设置的基本回退。缺少某个键时,pt-BR 用户会看到英语,而不是 pt-PT。rails-locale-chain 添加可配置的深度合并链,使地区用户始终看到最接近的可用翻译。
# Lazy lookups use the controller/action as scope
# app/views/products/index.html.erb
# Instead of t('products.index.title'), just use:
<h1><%= t('.title') %></h1>
<p><%= t('.description') %></p>
# Rails looks up: products.index.title and products.index.description
# config/locales/en.yml
en:
products:
index:
title: "All Products"
description: "Browse our catalog"自动翻译
完成 Rails I18n 设置后,使用 AI 翻译 YAML 区域设置文件。i18n Agent 原生支持 YAML,将源区域设置文件交给它即可生成所有目标语言,并保留嵌套键、插值变量和复数形式。
# Gemfile
gem 'rails-locale-chain'
# config/initializers/locale_chain.rb
Rails.application.config.i18n.fallbacks = {
'pt-BR': ['pt', 'en'],
'zh-Hant-TW': ['zh-Hant', 'zh', 'en'],
'es-419': ['es', 'en'],
}
# The gem deep-merges translations across the chain
# pt-BR -> pt -> en
# Missing keys in pt-BR are filled from pt, then en常见问题
InvalidPluralizationData 错误
在视图外使用惰性查找
YAML 语法错误导致所有翻译失效
立即试用 i18n Agent
将翻译文件拖放到此处
JSON, YAML, PO, XML, CSV, Markdown, Properties
或点击选择文件
目标语言