Snabbreferens

Rails internationalisering (i18n) fusklapp

En snabb referensguide för Rails i18n: översättningar, lokaliserade datum, pluralisering, scoped lookups och YAML-ordlistor.

· Publicerad

Rails ramverk för internationalisering (i18n) ger lokalisering för strängar, siffror, valutor och datum genom vanliga YAML-ordlistor.

Grundläggande översättnings- & datumhelpers

<!-- Översätt en nyckel -->
<%= t('welcome.title') %>

<!-- Lazy scoped-översättning baserad på aktuell controller/action -->
<!-- I app/views/articles/index.html.erb: söker upp articles.index.heading -->
<%= t('.heading') %>

<!-- Lokalisera datum och tider -->
<%= l(Time.now, format: :short) %>
<%= l(Date.today, format: :long) %>

Variabelinterpolering och pluralisering

# 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."

I mallen:

<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>

Ställ in nuvarande språk (Locale)

I 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översättningar

en:
  activerecord:
    models:
      user: "Customer"
    attributes:
      user:
        email: "Email Address"
        role: "Account Role"

I vyer:

<%= User.model_name.human %>
<!-- => "Customer" -->

<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->

Referenser

Relaterade ämnen