Das Rails Internationalization (i18n) Framework bietet Lokalisierung für Strings, Zahlen, Währungen und Datumsangaben über Standard-YAML-Wörterbücher.
Grundlegende Übersetzungs- & Datums-Helper
<!-- Schlüssel übersetzen -->
<%= t('welcome.title') %>
<!-- Lazy-Scoped-Übersetzung basierend auf aktuellem Controller/Action -->
<!-- In app/views/articles/index.html.erb: schlägt articles.index.heading nach -->
<%= t('.heading') %>
<!-- Datums- und Zeitangaben lokalisieren -->
<%= l(Time.now, format: :short) %>
<%= l(Date.today, format: :long) %>
Variableninterpolation & Pluralisierung
# config/locales/en.yml
en:
greetings:
hello: "Hello, %{name}!"
inbox:
unread_messages:
one: "You have 1 unread message."
other: "You have %{count} unread messages."
zero: "You have no unread messages."
Im Template:
<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>
Aktuelle Locale festlegen
In ApplicationController:
class ApplicationController < ActionController::Base
before_action :set_locale
private
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options
{ locale: I18n.locale }
end
end
Active Record Modell-Übersetzungen
en:
activerecord:
models:
user: "Customer"
attributes:
user:
email: "Email Address"
role: "Account Role"
In Views:
<%= User.model_name.human %>
<!-- => "Customer" -->
<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->