
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
或點擊選擇檔案
目標語言