
Rails i18n: complete internationalisatiehandleiding voor Ruby on Rails
Van je eerste localebestand tot productie: configureer Rails I18n, gebruik de hulpfunctie t(), verwerk CLDR-meervoudsvormen, los veelvoorkomende valkuilen op en voeg slimme terugvalketens toe.
De architectuur van Rails I18n begrijpen
Rails wordt geleverd met de I18n-gem. Vertaalbestanden staan als YAML- (standaard) of Ruby-bestanden in config/locales/. Het framework biedt de hulpfunctie t() (een alias voor I18n.translate) in views, controllers, modellen en mailers. Rails I18n is bewust eenvoudig en verwerkt standaard basisvertalingen, interpolatie en meervoudsvormen.
# 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
endLocale-instellingen configureren
Stel default_locale, available_locales en het terugvalgedrag in config/application.rb of een initializer in. Configureer localedetectie in ApplicationController en gebruik before_action om de locale in te stellen op basis van de URL, sessie, cookie of Accept-Language-header.
# 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"De hulpfunctie t() gebruiken
De hulpfunctie t() is overal in Rails beschikbaar: in views, controllers, modellen, mailers en taken. De functie accepteert een sleutel, optionele interpolatievariabelen en opties zoals standaardwaarden en bereik. In views ondersteunt Rails uitgestelde zoekacties die sleutels automatisch beperken tot de huidige controller en actie.
# 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')) %>Meervoudsvormen verwerken
Rails I18n gebruikt de CLDR-meervoudscategorieën zero, one, two, few, many en other. Engels heeft alleen one en other nodig, maar andere talen vereisen meer vormen. Definieer meervoudsvertalingen als geneste YAML-sleutels onder de aantalcategorieën die je doeltalen nodig hebben.
# 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) %>Locale-fallbackketens toevoegen
De ingebouwde I18n.fallbacks van Rails biedt alleen eenvoudige terugval van een regionale naar de standaardlocale. Een gebruiker met pt-BR en een ontbrekende sleutel ziet Engels in plaats van pt-PT. rails-locale-chain voegt configureerbare ketens met diepe samenvoeging toe, zodat regionale gebruikers altijd de dichtstbijzijnde beschikbare vertaling zien.
# 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"Vertalingen automatiseren
Nu je Rails I18n-configuratie klaar is, kun je YAML-localebestanden met AI vertalen. i18n Agent ondersteunt YAML rechtstreeks: verwijs naar het bronlocalebestand en de tool genereert alle doeltalen met behoud van geneste sleutels, interpolatievariabelen en meervoudsvormen.
# 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 enVeelvoorkomende valkuilen
InvalidPluralizationData-fouten
Uitgestelde zoekacties buiten views
YAML-syntaxisfouten maken alle vertalingen onbruikbaar
Probeer i18n Agent nu
Zet je vertaalbestand hier neer
JSON, YAML, PO, XML, CSV, Markdown, Properties
of klik om een bestand te selecteren
Doeltalen